Tom
Tom

Reputation: 53

Remove last repeated word occurence in a string PHP

I need remove last repeated word in a string, example:

Last repeat word is: all/

String input examples:

The result should be always: item1/item2/

Upvotes: 0

Views: 397

Answers (2)

mario
mario

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

steveo225
steveo225

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

Related Questions