我有一个字符串,下面是来自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'[).*(?='])
演示$re = "/(?<='$x'[).*(?='])/";
$str = "Sample String";
preg_match_all($re, $str, $matches);
LookBehind
-匹配模式应该在$x[
—(?<='$x'[)
之后。如果要匹配的模式是XYZ
,那么在XYZ
后面应该存在$X
。.*
在最后一个匹配模式之后匹配所有LookAhead
-(?='])
-匹配]
由于PHP在双引号字符串中插入变量(变量以美元符号开始),因此将preg_match_all
正则表达式放在单引号字符串中可以防止这种情况。尽管"$"在正则表达式中仍然被转义,因为它是正则表达式的锚字符。
在这种情况下,/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 )