2013-07-24 69 views
1

我遇到了匹配[*]的问题,有时会出现这种问题,有时候不会。任何人都有建议?PHP - 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); 

输出: 你好$这 - >行[测试],多好$这个 - >行[TEST2]是>行[日] [*]为$这个 - 周一

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

感谢

+0

尝试'/(\ $这个 - >行\(\ [^ \)] * \)) /' – Orangepill

+0

试试这个,preg_match_all('/\$this->row(\[.*?'])(\[\*\])?/',$ name,$ match); – Nightmare

+0

这两个不匹配 – Karassik

回答

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

OUTPUT:

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

完美的感谢。我一直在搞这个。最后 ?使以前的细分是可选的? – Karassik

+0

不客气。是的,这是正确的??使前面的组是可选的。 – anubhava