PHP-Preg_match_所有可选匹配
我在匹配[*]时遇到问题,有时存在,有时不存在。有人有什么建议吗PHP-Preg_match_所有可选匹配,php,regex,preg-match-all,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, $ma
$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]”结束。我猜[*]/添加了一个通配符。在匹配到[]之前,需要检查下一个字符是否为[]。有人吗
感谢
[
,]
和*
是正则表达式中的特殊元字符,您需要对它们进行转义。此外,您还需要根据您的问题将最后一个[]
设置为可选
根据这些建议,以下建议应该有效:
$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][*]"
}
}
试一下
/(\$this->row\(\[^\)]*\)/
试一下这个,preg\u match\u all('/\$this->row([.*?])([*])?/,$name,$match);这两个都不匹配,谢谢。我有一段时间不明白了。最后一个?让上一个部分可选?不客气。是的。?
让上一个部分可选。