-4

Possible Duplicate:
remove duplicate from string in PHP

Have a string like:

$str = "1 - 1 - 2 - 3 - 1 - 4 - 3 - 1 - 2 - 5 - 6 - 4";

and i need to get

$str = "1 - 2 - 3 - 4 - 5 - 6";

any help.. :(

Community
  • 1
  • 1
PHP Ferrari
  • 15,754
  • 27
  • 83
  • 149
  • I've downvoted, as it is much better to explain what you've tried, ideally with a code sample. Sitting down with a manual and giving things a go _first_ is the best way to learn `:)` – halfer Mar 23 '12 at 16:38

5 Answers5

5

Example/Demo:

$elements = array_unique(explode(' - ', $input));
sort($elements);
$str = implode(' - ', $elements);
hakre
  • 193,403
  • 52
  • 435
  • 836
Brian
  • 15,599
  • 4
  • 46
  • 63
1

I've just had a quick look around and with the code from

This would work for you.

You can see a demo of the example.

Community
  • 1
  • 1
ojjwood
  • 166
  • 1
  • 4
0

Something like this:

<?php
$str = str_replace(' - ', ',', $str);
$items = array_unique(explode(',', $str));
echo implode(' - ', $items);
?>

I've swapped the space-hifen-space delimiter so you can see what's going on in intermediate steps - but you can explode on that immediately if you wish.

halfer
  • 19,824
  • 17
  • 99
  • 186
0

If you have to make new string with unique values you would try this:

implode(' - ', array_unique(explode(' - ', $array)));
Bartek Kobyłecki
  • 2,365
  • 14
  • 24
0

yeah, I would do something like this:

$strArray = explode(' - ',$str);
str = array_unique($strArray);

Or something to that effect.

Thomas Wright
  • 1,309
  • 1
  • 9
  • 15