how to remove only real duplicates from preg_match output?

大憨熊 提交于 2019-12-25 11:59:09

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!