【问题标题】:PHP - Preg_match_all optional matchPHP - Preg_match_all 可选匹配
【发布时间】:2013-07-24 03:32:35
【问题描述】:

我在匹配 [*] 时遇到问题,有时存在有时不存在。有人有建议吗?

$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[today][*] 是星期一

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]' 结束。我猜 [*]/ 添加了一个通配符。在匹配到 [] 之前,不知何故需要检查下一个字符是否是 [。有人吗?

谢谢

【问题讨论】:

  • 试试/(\$this->row\(\[^\)]*\))/
  • 试试这个,preg_match_all( '/\$this->row([.*?])([*])?/', $name, $match );
  • 这两个都不匹配

标签: php regex preg-match-all


【解决方案1】:

[]* 是正则表达式中的特殊元字符,您需要对它们进行转义。您还需要根据您的问题将最后一个 [] 设为可选。

遵循这些建议应该可以:

$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][*]"
  }
}

【讨论】:

  • 非常感谢。我搞砸了一段时间。最后 ?将上一段设为可选?
  • 不客气。是的,这是正确的? 使上一组成为可选。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-05-01
  • 2016-04-03
  • 2011-08-07
  • 1970-01-01
  • 2011-10-01
相关资源
最近更新 更多