2011-04-03 32 views
1

你好,我想獲得以下所有的唯一匹配。我該怎麼做?有什麼方法可以只用preg_match_all獲得唯一的匹配嗎?

preg_match_all('#http://[\S]+(?:jpe?g|png|gif)#is', $content, $filtered); 

$filtered = array_unique($filtered[0]); 
foreach($filtered as $value){ 
${'varpics' . $i} .= '<img width="200px" height="200px" src="'.$value.'"><br>'; } 

我仍然得到雙重比賽。

回答

3

No.只需將結果通過array_unique即可。

除非你想得到真正的幻想preg_replace_callback並推動比賽成集。完美的我


<?php 
$content = <<<HTML 
<img src="http://www.mysite.com/image1.jpg" /> 
<img src="http://www.mysite.com/image2.gif" /> 
<img src="http://www.mysite.com/image1.jpg" /> 
HTML; 

preg_match_all('#http://[\S]+(?:jpe?g|png|gif)#is', $content, $matches); 
$images = array_unique($matches[0]); 

var_dump($images); 

作品。輸出:

array 
    0 => string 'http://www.mysite.com/image1.jpg' (length=32) 
    1 => string 'http://www.mysite.com/image2.gif' (length=32) 

儘管你的代碼有很多其他的錯誤。例如,$i在哪裏定義?爲什麼你想要定義這樣的變量?使用數組,而不是使用數字附加的名稱...我甚至不確定這是否是有效的語法。

+1

我推薦array_unique,它是更乾淨的方法。 – Christian 2011-04-03 23:07:13

+0

您好,馬克。你能檢查我的更新代碼嗎?我仍然得到雙重結果 – EnexoOnoma 2011-04-03 23:07:15

+0

@Punkis:查看更新。 – mpen 2011-04-03 23:18:27

相關問題