0

是的,我知道array_unique功能,但问题是匹配项在我的搜索词中可能有合法的重复项,例如:

$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
)
4

2 回答 2

2

这是我对您的问题的解决方案:

unset($matches[0]);
$matches = array_unique($matches);
于 2015-01-26T19:41:51.520 回答
1

我自己找到了,解决方案是一个删除后续键的while循环,它所在的键不是数字:

while (next($match) !== false) {
  if (!is_int(key($match))) {
    next($match);
    unset($m[key($match)]);
  }
}
reset($match);
于 2012-11-24T18:31:18.087 回答