2010-12-22 53 views
3

我有一個正則表達式模式,用於搜索文本文件中的單詞。我如何忽略重複?忽略正則表達式中的重複項

例如,看看這個代碼

$pattern = '/(lorem|ipsum|daboom|pahwal|ababaga)/i'; 
$num_found = preg_match_all($pattern, $string, $matches); 

echo "$num_found match(es) found!"; 
echo "Matched words: " . implode(',', $matches[0]); 

如果我有一個以上的說LOREM在文章中,輸出將是這樣的

5 matches found! 
Matched words: daboom,lorem,lorem,lorem,lorem 

我想該模式只發現第一次出現,而忽略其餘部分,所以輸出應爲:

2 matches found! 
Matched words: daboom,lorem 

回答

6

$matches[0]上執行array_unique。如果您希望獨特區域不區分大小寫,可能還需要array_mapstrtolower

$pattern = '/(lorem|ipsum|daboom|pahwal|ababaga)/i'; 
preg_match_all($pattern, $string, $matches); 
$matches = $matches[0]?array_unique(array_map('strtolower', $matches[0])):array(); 

echo count($matches)." match(es) found!"; 
echo "Matched words: " . implode(',', $matches); 
+0

*拍打額頭*爲什麼我沒有想到這一點? – HyderA 2010-12-22 10:07:28