2016-09-02 57 views
1

我想不過我只收到一個preg_match_all不匹配所有的可能性

這裏找回所有比賽是我的字符串

$html = '<p> This is my Home Page.</p><p><span style="line-height: 1.42857;">{{ type="slider" }} </span></p><p> </p>'; 

如果你看到的字符串包含{{ type="slider" }},現在如果我寫這個字符串只有一次我得到了我的預期結果, 但是如果我在html中多次寫入它就像{{ type="slider" }}{{ type="banned" }}{{ type="testimonial" }}

$html = '<p> This is my Home Page.</p><p><span style="line-height: 1.42857;">{{ type="slider" }} {{ type="banner" }} {{ type="testimonial" }} </span></p><p> </p>'; 

,並嘗試我的字符串{{ type=" ???? " }}內得到的數值就說明怪異的結果

我使用這下面的代碼。

preg_match_all('/{{ type=\"(.+)\" }}/', $html, $matches, PREG_SET_ORDER); 
echo "<pre>"; 
print_r($matches); 
foreach ($matches as $val) { 
    echo "matched: ". $val[0] . "<br/>"; 
    echo "My Value" . $val[1] . "<br/>"; 
} 

當前結果:

Array 
(
    [0] => Array 
     (
      [0] => {{ type="slider" }} {{ type="banner" }} {{ type="testimonial" }} 
      [1] => slider" }} {{ type="banner" }} {{ type="testimonial 
     ) 

) 
matched: {{ type="slider" }} {{ type="banner" }} {{ type="testimonial" }} 
My Value : slider" }} {{ type="banner" }} {{ type="testimonial 

我與{{ type="" }}

之間寫有{{ type="slider" }}只有我得到這個結果是完美的數值數組期待的結果。

Array 
(
    [0] => Array 
     (
      [0] => {{ type="slider" }} 
      [1] => slider 
     ) 

) 
matched: {{ type="slider" }} 
My Value : slider 

有什麼想法嗎?

對不起,我的英語不好。

+0

嘗試'preg_match_all('/ {{type = \「(。+?)\」}}/mi',$ html,$ matches,PREG_SET_ORDER);' – zanderwar

回答

4

你需要讓你的正則表達式匹配非貪婪加上無論是?

preg_match_all('/{{ type=\"(.+?)\" }}/', $html, $matches, PREG_SET_ORDER); 

U修改:

preg_match_all('/{{ type=\"(.+)\" }}/U', $html, $matches, PREG_SET_ORDER); 
+0

Perfectttt !!!!!!!!!! !...謝謝 –

+0

http://stackoverflow.com/questions/39286071/preg-match-all-find-match-multiple-stings-and-get-the-values-written-in-double-q你能回答這個問題 ? –

1

你當前越來越是相當正常的,因爲默認情況下,你的正則表達式是貪婪的,即/{{ type="(.+)"}} /尋找最長的字符串,從{{ type="開始並以}}結尾。

這裏的另一個答案建議你添加一個「不貪婪」的量詞?,它可以工作,但它不是最好的解決方案(因爲它需要更多的正則表達式引擎)。

相反,您最好只在您的正則表達式中用([^"]+)替換(.+)

+0

我的正則表達式的能力很糟糕,所以我只是想讓你的答案upvote :) – Mike

+0

好吧,但這種方式我無法得到在type =「」中寫入的值。 –

+0

@PunitGajjar可能因爲你嘗試了我的第一個版本,我忘記了捕獲括號!看看當前的版本。 – cFreed