How to remove duplicate substrings from a string

I have a line like this:

'' Spain, France, Spain, Germany, France, Spain

you need only unique substrings

"Spain, France, Germany

the only way I could think of is to convert to an array and vice versa:

$countries = "spain,france,spain,germany,france,spain";
$country = implode( ",", array_unique( explode( ",", $countries ) ) );

Another / correct way to do this?

+4
source share
1 answer

I think your way of doing this is good. But you need to keep track of the spaces between the comma and the word. To do this, simply add:
$countries = str_replace(' ', '', $countries);

If you expect spaces , and you should remove them with regular expressions:
$countries = preg_replace('/\s/', '', $countries);

:

  • - .
  • , , ..

0

All Articles