I have a string that is something like this:
$string = "Item 1|Item 2|Item 3|Item 4|Item 5"
What is the best way to iterate through this string and remove duplicates. So for example it would know that each portion of code to compare would be between the ‘|’ characters.
It would select Item1 and preg_replace() the rest of the string with that Item. Then it would look at the next Item (Item2) and preg_replace() the rest of the string with that Item.
The tricky part is if Item 1 == Item 2. Then, the algorithm will replace Item 2 and Item 3 will be the next Item to look at.
I have tried a couple methods but nothing is working. Any ideas? Thanks!
If I understand correctly, ignoring all your stuff about
preg_replace()if you are really just looking to remove duplicates, then use a few array operations.explode()it on the|into an array. Filter it witharray_unique()andimplode()it back into pipe-delimited string: