How replace all repeated occurrences of string for the single same:
I have string like:
1-string-2-string-3-string-55-otherstring-66-otherstring
I need replace for:
1-2-3-string-55-66-otherstring
How can I do that?
How replace all repeated occurrences of string for the single same:
I have string like:
1-string-2-string-3-string-55-otherstring-66-otherstring
I need replace for:
1-2-3-string-55-66-otherstring
How can I do that?
You could do this:
$str = '1-string-2-string-3-string-55-otherstring-66-otherstring';
print_r(implode('-', array_reverse(array_unique(array_reverse(explode('-', $str))))));
Or using Regular Expressions:
(\w++)-?(?=.*\b\1\b)
Breakdown:
(\w++)
Match and capture a word-?
Match following hyphen if any(?=
Start of positive lookahead
.*\b\1\b
Recent captured word should repeat)
End of lookaheadPHP code:
echo preg_replace('~(\w++)-?(?=.*\b\1\b)~', '', $str);