chaimp chaimp - 3 months ago 23
PHP Question

What's the best way to remove duplicates from a string in PHP (or any language)?

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.

Let's say you have the following strings:

  • 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

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