繁体   English   中英

PHP-Preg_match_all可选匹配

[英]PHP - Preg_match_all optional match

我在匹配[*]时遇到问题,该[*]有时在那里,有时没有。 有人有建议吗?

$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 );  

输出:hello $ 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]'结尾。 我猜[*] /添加了通配符。 某种程度上需要在匹配[]之前检查下一个字符是否为[。 任何人?

谢谢

[]*是正则表达式中的特殊元字符,您需要对其进行转义。 另外,您还需要根据您的问题将last []可选。

遵循以下建议应该可以起作用:

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM