从PHP(或任何语言)中的字符串中删除重复的最佳方式是什么? [英] What's the best way to remove duplicates from a string in PHP (or any language)?

查看:131
本文介绍了从PHP(或任何语言)中的字符串中删除重复的最佳方式是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在寻找从字符串中删除重复的最为人熟知的算法。我可以想到这样做的许多方法,但我正在寻找一种以特别有效的方式而闻名的解决方案。

I am looking for the best known algorithm for removing duplicates from a string. I can think of numerous ways of doing this, but I am looking for a solution that is known for being particularly efficient.

假设你有以下字符串:


  • Lorem Ipsum Lorem Ipsum

  • Lorem Lorem Lorem

  • Lorem Ipsum Dolor Lorem Ipsum Dolor Lorem Ipsum Dolor

  • Lorem Ipsum Lorem Ipsum
  • Lorem Lorem Lorem
  • Lorem Ipsum Dolor Lorem Ipsum Dolor Lorem Ipsum Dolor

我希望这个算法可以分别输出:

I would expect this algorithm to output for each (respectively):


  • Lorem Ipsum

  • Lorem

  • Lorem Ipsum Dolor

  • Lorem Ipsum
  • Lorem
  • Lorem Ipsum Dolor

请注意,我在做这在PHP中,万一有人知道任何内置的PHP函数可以帮助这个。

Note, I am doing this in PHP, in case anybody is aware of any built in PHP functions that can help with this.

谢谢!

推荐答案

$arr = explode( " " , $string );
$arr = array_unique( $arr );
$string = implode(" " , $arr);

这篇关于从PHP(或任何语言)中的字符串中删除重复的最佳方式是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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