Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/php/289.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/regex/20.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
PHP-Preg_match_所有可选匹配_Php_Regex_Preg Match All - Fatal编程技术网

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);这两个都不匹配,谢谢。我有一段时间不明白了。最后一个?让上一个部分可选?不客气。是的。
让上一个部分可选。