从 PHP 中的字符串中删除重复项

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2613063/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 07:07:04  来源:igfitidea点击:

remove duplicate from string in PHP

phpstringduplicates

提问by Adnan

I am looking for the fastest way to remove duplicate values in a string separated by commas.

我正在寻找删除以逗号分隔的字符串中重复值的最快方法。

So my string looks like this;

所以我的字符串看起来像这样;

$str = 'one,two,one,five,seven,bag,tea';

I can do it be exploding the string to values and then compare, but I think it will be slow. what about preg_replace() will it be faster? Any one did it using this function?

我可以将字符串分解为值然后进行比较,但我认为它会很慢。那么 preg_replace() 会更快吗?有人用过这个功能吗?

回答by Felix Kling

The shortest code would be:

最短的代码是:

$str = implode(',',array_unique(explode(',', $str)));

If it is the fastest... I don't know, it is probably faster then looping explicitly.

如果它是最快的......我不知道,它可能比显式循环更快。

Reference: implode, array_unique, explode

参考:implode, array_unique,explode

回答by mickmackusa

Dealing with: $string = 'one,two,one,five,seven,bag,tea';

处理: $string = 'one,two,one,five,seven,bag,tea';

If you are generating the string at any point "up script", then you should be eliminating duplicates as they occur.

如果您在“up script”的任何时候生成字符串,那么您应该在出现重复项时消除它们。

Let's say you are using concatenation to generate your string like:

假设您正在使用连接来生成您的字符串,如:

$string='';
foreach($data as $value){
    $string.=(strlen($string)?',':'').some_func($value);
}

...then you would need to extract unique values from $stringbased on the delimiter (comma), then re-implode with the delimiter.

...然后您需要$string根据分隔符(逗号)从中提取唯一值,然后使用分隔符重新内爆。



I suggest that you design a more direct method and deny duplicates inside of the initial foreach loop, like this:

我建议您设计一个更直接的方法并拒绝初始 foreach 循环内的重复项,如下所示:

foreach($data as $value){
    $return_value=some_func($value);  // cache the returned value so you don't call the function twice
    $array[$return_value]=$return_value;  // store the return value in a temporary array using the function's return value as both the key and value in the array.
}
$string=implode(',',$array);  // clean: no duplicates, no trailing commas

This works because duplicate values are never permitted to exist. All subsequent occurrences will be used to overwrite the earlier occurrence. This function-less filter works because arrays may not have two identical keys in the same array(level).

这是有效的,因为永远不允许存在重复值。所有后续事件都将用于覆盖较早的事件。此无函数过滤器有效,因为数组在同一数组(级别)中可能没有两个相同的键。

Alternatively, you can avoid "overwriting" array data in the loop, by calling if(!isset($array[$return_value])){$array[$return_value]=$return_value;}but the difference means calling the isset()function on every iteration. The advantage of using these associative key assignments is that the process avoids using in_array()which is slower than isset().

或者,您可以通过调用来避免在循环中“覆盖”数组数据,if(!isset($array[$return_value])){$array[$return_value]=$return_value;}但不同之处是isset()在每次迭代时调用该函数。使用这些关联键分配的优点是该过程避免使用in_array()比 慢的isset()

All that said, if you are extracting a column of data from a 2-dimensional array like:

综上所述,如果您从二维数组中提取一列数据,例如:

$string='';
foreach($data as $value){
    $string.=(strlen($string)?',':'').$value['word'];
}

Then you could leverage the magic of array_column()without a loop like this:

然后,你可以利用的魔法array_column()没有环这样的

echo implode(',',array_column($str,'word','word'));


And finally, for those interested in micro-optimization, I'll note that the single call of array_unique()is actually slower than a few two-function methods. Read herefor more details.

最后,对于那些对微优化感兴趣的人,我会注意到,单个调用array_unique()实际上比几个双功能方法慢。 阅读此处了解更多详情。

The bottomline is, there are many ways to perform this task. explode->unique->implodemay be the most concise method in some cases if you aren't generating the delimited string, but it is not likely to be the most direct or fastest method. Choose for yourself what is best for your task.

最重要的是,有很多方法可以执行此任务。explode->unique->implode如果您不生成分隔字符串,在某些情况下可能是最简洁的方法,但它不太可能是最直接或最快的方法。为自己选择最适合您的任务的方法。