2012-11-29 40 views
0

我試圖用preg_match_all獲得所有{{product.smth}},但是如果我在一行中沒有這樣的內容,我會得到錯誤的結果。preg_match_all問題

例子:

$smth = '<name>{{product.name}}</name><getname>{{product.getName()}}</getname>'; 

$pattern = '/\{\{product\.(.*)\}\}/'; 
preg_match_all($pattern, $smth, $matches); 

//returns '{{product.name}}</name><getname>{{product.getName()}}' 
//instad of '{{product.name}}' and '{{product.getName()}}' 

什麼IAM做錯了什麼?請幫忙。

+0

使用'/ U'修飾符。 –

+0

@Ωmega我更喜歡修飾符:)注意,ungreedy只是與它切換,所以'/.*?/ U'就是貪婪的例子。 –

回答

3

問題是repetition is greedy。要麼使它ungreedy使用.*?或更好的:禁止對}字符重複:

$pattern = '/\{\{product\.([^}]*)\}\}/'; 

如果你想允許單}在價值(如{{product.some{thing}here}}),相當於解決方案使用negative lookahead

$pattern = '/\{\{product\.((?:(?!\}\}).)*)\}\}/'; 

對於每一個字符包含在.*它會檢查該字符並不標誌着一個}}的開始。

1

我認爲,如果你改變.*.*?它會工作這將使貪婪懶惰來代替,而它會嘗試儘可能少的匹配 - 所以,直到的}}第一次出現,而不是持續。

+0

難道只是稱爲不真實嗎?否則你會從一個罪到另一個:) –

+0

_拉齊量詞有時也被稱爲「不理智」或「不情願」_來源:http://www.regular-expressions.info/repeat.html – Halcyon