2012-11-11 32 views
0

是的,我知道array_unique功能,但事情是,比賽可能在我的搜索詞合法的重複,例如:如何從preg_match輸出中只刪除真正的重複項?

$str = "fruit1: banana, fruit2: orange, fruit3: banana, fruit4: apple, fruit5: banana"; 
preg_match("@fruit1: (?<fruit1>\w+), fruit2: orange, fruit3: (banana), fruit4: (?<fruit4>apple), fruit5: (banana)@",$str,$match); 
array_shift($match); // I dont need whole match 
print_r($match); 

輸出爲:

Array 
(
    [fruit1] => banana 
    [0] => banana 
    [1] => banana 
    [fruit4] => apple 
    [2] => apple 
    [3] => banana 
) 

所以這是真正的唯一的鑰匙重複是[0]和[2]但array_unique給出:

Array 
(
    [fruit1] => banana 
    [fruit4] => apple 
) 
+1

爲什麼只有[0]和[2]的重複? – GBD

+0

因爲如果一個正則表達式有一個命名範圍,它會產生兩個鍵,一個命名和一個整數,但未命名的範圍只給出整數鍵。一個命名的和另一個未命名的範圍可以通過純粹的機會具有相同的值。所以使用array_unique是不安全的。 – rsk82

+0

爲什麼只有'0'和'1'是重複的,真的沒有意義。'3'怎麼辦? – Baba

回答

1

我發現它自己,解決方案是一個while循環刪除SUBSEQ uent關鍵是,它是不是數字:

while (next($match) !== false) { 
    if (!is_int(key($match))) { 
    next($match); 
    unset($m[key($match)]); 
    } 
} 
reset($match); 
2

這是我對你的問題的解決方案:

unset($matches[0]); 
$matches = array_unique($matches);