问题
Yes I know array_unique
function, but the thing is that match might have a legitimate duplicates in my search term for example:
$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);
output is:
Array
(
[fruit1] => banana
[0] => banana
[1] => banana
[fruit4] => apple
[2] => apple
[3] => banana
)
So the only keys that are real duplicates are [0] and [2] but array_unique
gives:
Array
(
[fruit1] => banana
[fruit4] => apple
)
回答1:
This is my solution for your problem:
unset($matches[0]);
$matches = array_unique($matches);
回答2:
I found it myself, solution is a while loop that deletes subsequent key is one that it is at is not numerical:
while (next($match) !== false) {
if (!is_int(key($match))) {
next($match);
unset($m[key($match)]);
}
}
reset($match);
来源:https://stackoverflow.com/questions/13333431/how-to-remove-only-real-duplicates-from-preg-match-output