从 PHP 中的字符串中删除重复项 [英] remove duplicate from string in PHP

查看:19
本文介绍了从 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

这篇关于从 PHP 中的字符串中删除重复项的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆