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

2022-01-10 00:00:00 string duplicates php

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

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';

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

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?

推荐答案

最短的代码应该是:

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

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

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

参考:implode, array_unique, explode

相关文章