2013-07-24 70 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