-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.. :(

1
  • 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 :) Commented Mar 23, 2012 at 16:38

5 Answers 5

5

Example/Demo:

$elements = array_unique(explode(' - ', $input));
sort($elements);
$str = implode(' - ', $elements);
Sign up to request clarification or add additional context in comments.

1 Comment

Ah sorted as well, good spot.
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.

Comments

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.

Comments

0

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

implode(' - ', array_unique(explode(' - ', $array)));

Comments

0

yeah, I would do something like this:

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

Or something to that effect.

1 Comment

errr, you probably want to implode that back to $str :P

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.