2016-09-02 52 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