4

I have a string like this:

'spain,france,spain,germany,france,spain'

need to have only unique substrings

'spain,france,germany'

the only way I could think of was this converting to an array and back:

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

Another/correct way to do it?

Leo
  • 78
  • 1
  • 6
  • 7
    Possible duplicate of [remove duplicates from comma separated string](http://stackoverflow.com/questions/5134176/remove-duplicates-from-comma-separated-string) – erikvimz May 23 '16 at 11:04
  • only if a source string may contain space after comma, you will need other solution – splash58 May 23 '16 at 11:18
  • @splash58 the source string may have spaces after comma, will the other solution be better/faster? – Leo May 23 '16 at 11:44

1 Answers1

0

I think your way to do this is good. But you need to watchout for spaces between comma and word. To do this just add:
$countries = str_replace(' ', '', $countries);

If you expect whitespaces to be there aswell you should remove them using regular expressions:
$countries = preg_replace('/\s/', '', $countries);

If you don't know the difference between space and whitespace:

  • Space is just regular space character between other characters
  • Whitespace can be space, tabulation, new line etc.

source

Community
  • 1
  • 1
Jakub Stasiak
  • 113
  • 1
  • 11