PHP - Preg_match_all可选匹配

时间:2013-07-24 03:32:36

标签: php regex preg-match-all

我遇到的问题与[*]相匹配,有时会出现问题,有时则没有。有人有建议吗?

$name = 'hello $this->row[today1][] dfh fgh df $this->row[test1] ,how good $this->row[test2][] is $this->row[today2][*] is monday'; 
echo $name."\n"; 
preg_match_all( '/\$this->row[.*?][*]/', $name, $match ); 
var_dump( $match );  

输出: 你好$ this-> row [test],多好$ this-> row [test2]是$ this-> row [今天] [*]是星期一

array (
 0 => 
  array (
   0 => '$this->row[today1][*]',
   1 => '$this->row[test1] ,how good $this->row[test2][*]',
   2 => '$this->row[today2][*]',
  ),
)

现在[0] [1]匹配过多,因为它匹配到下一个'[]'而不是以'$ this-> row [test]'结尾。我猜[*] /添加了一个通配符。不知何故需要检查下一个字符是否[在与[]匹配之前。任何人吗?

由于

1 个答案:

答案 0 :(得分:0)

[]*是正则表达式中的特殊元字符,您需要将其转义。您还需要根据您的问题选择最后[]个可选项。

遵循以下建议应该有效:

$name = 'hello $this->row[today1][] dfh fgh df $this->row[test1] ,how good $this->row[test2][] is $this->row[today2][*] is monday'; 
echo $name."\n"; 
preg_match_all( '/\$this->row\[.*?\](?:\[.*?\])?/', $name, $match ); 
var_dump( $match ); 

<强>输出:

array(1) {
  [0]=>
  array(4) {
    [0]=>
    string(20) "$this->row[today1][]"
    [1]=>
    string(17) "$this->row[test1]"
    [2]=>
    string(19) "$this->row[test2][]"
    [3]=>
    string(21) "$this->row[today2][*]"
  }
}