Reputation: 53
I need remove last repeated word in a string, example:
Last repeat word is: all/
String input examples:
item1/item2/all/
item1/item2/all/all/all/
item1/item2/all/all/all/all/
The result should be always: item1/item2/
Upvotes: 0
Views: 397
Reputation: 145482
If those "words" are always separated by slash, then it's as simple as a regex with a backreference:
$str = preg_replace('#\b(\w+/)\1+$#', '', $str);
// here \b could be written as (?<=/) more exactly
Or if all
is a fixed string to look for:
$str = preg_replace('#/(all/)+$#', '/', $str);
Upvotes: 5
Reputation: 11882
I am assuming you want the last word removed, and any repeats of it
$list = explode('/', $str);
if(end($list) == '') array_pop($list); // remove empty entry on end
$last = array_pop($list);
while(end($list) == $last) array_pop($list);
$str = implode('/', $list); // put back together
Upvotes: 2