Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/regex/19.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
在PHP中捕获子字符串后方括号中的文本_Php_Regex - Fatal编程技术网

在PHP中捕获子字符串后方括号中的文本

在PHP中捕获子字符串后方括号中的文本,php,regex,Php,Regex,我有下面这样的字符串,它来自DB $temp=Array(true); if($x[211] != 15) $temp[] = 211; if($x[224] != 1) $temp[] = 211; if(sizeof($temp)>1) { $temp[0]=false; } return $temp; 我需要找到方括号内的所有值,后跟$x变量。即211和224 我尝试了下面的代码,这是我在这个网站上找到的答案,但它返回了方括号中的所有值,包括后面跟着$tem

我有下面这样的字符串,它来自DB

$temp=Array(true);
if($x[211] != 15)
    $temp[] = 211;
if($x[224] != 1)
    $temp[] = 211;
if(sizeof($temp)>1) {
    $temp[0]=false;
}
return $temp;
我需要找到方括号内的所有值,后跟$x变量。即211和224

我尝试了下面的代码,这是我在这个网站上找到的答案,但它返回了方括号中的所有值,包括后面跟着$temp变量的值

preg_match_all("/\[(.*?)\]/", $text, $matches);
print_r($matches[1]);
请让我知道如何获得所需的结果?

RegEx

(?<=\$x\[).*(?=\])

(?由于PHP在双引号字符串中插入变量(变量以美元符号开头),因此将
preg_match_all
regex放在单引号字符串中可以防止这种情况。尽管“$”在regex中仍然转义,因为它是regex锚字符

在这种情况下,
/x\[(.*?\]/
也可以工作,但我认为越精确越好

$text = '
$temp=Array(true);
if($x[211] != 15)
    $temp[] = 211;
if($x[224] != 1)
    $temp[] = 211;
if(sizeof($temp)>1) {
    $temp[0]=false;
}
return $temp;
';

preg_match_all('/\$x\[(.*?)\]/', $text, $matches);
print_r($matches[1]);
输出:

Array ( [0] => 211 [1] => 224 )

“/\$x\[(.*?)]/”
给你什么可能的重复?@bloodyKnuckles-我在用“`/\$x[(.*?)]/``-`bloodyKnuckles测试后得到空数组-通过使用
preg\u match\u all(^x\[(.?)^,$text,$matches)得到解决方案);
。谢谢。你能解释一下为什么这是解决这个问题的好办法吗。@LIUFA-补充说明。
Array ( [0] => 211 [1] => 224 )