【问题标题】:Capturing text between square brackets after a substring in PHP在PHP中的子字符串之后捕获方括号之间的文本
【发布时间】:2014-07-01 22:00:47
【问题描述】:

我有来自 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]);

请告诉我怎样才能得到这个想要的结果?

【问题讨论】:

标签: php regex


【解决方案1】:

正则表达式

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

Demo

$re = "/(?<=\$x\[).*(?=\])/"; 
$str = "Sample String"; 

preg_match_all($re, $str, $matches);

说明

  • LookBehind - 匹配模式应该出现在$x[ --- (?&lt;=\$x\[) 之后。如果要匹配的模式是XYZ,那么XYZ后面应该存在$X

  • .* 匹配最后一个匹配模式之后的所有内容

  • LookAhead - (?=\]) - 匹配所有直到]

【讨论】:

  • 您能否解释一下为什么这是解决问题的好方法。
  • @LIUFA - 添加了解释。
【解决方案2】:

由于 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 )

【讨论】:

    猜你喜欢
    • 2012-04-23
    • 1970-01-01
    • 1970-01-01
    • 2018-02-07
    • 2014-12-04
    • 2013-04-25
    • 1970-01-01
    • 2016-03-24
    • 2016-08-30
    相关资源
    最近更新 更多