0

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/

Nightfirecat
  • 11,432
  • 6
  • 35
  • 51
Tom
  • 61
  • 6
  • 1
    Is this "last repeated word" known in advance, or do you have to dynamically figure out what the last repeated word is? – deceze Nov 14 '11 at 23:27
  • check the similar [quesiton](http://stackoverflow.com/questions/2613063/remove-duplicate-from-string-in-php) has already been answered. – Muhammad Saifuddin Nov 14 '11 at 23:35

2 Answers2

5

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);
mario
  • 144,265
  • 20
  • 237
  • 291
  • +1 Nice solution, I really need to learn regular expressions, except it doesn't work for the first example. A simple fix I assume. – steveo225 Nov 14 '11 at 23:40
  • True. If the searched word is fixed, then `all` could replace `\w+`. And if it doesn't need to be repeated actually, then `\1*` instead of `\1+` would do. Not sure about OPs use case (looks like path names somewhat). – mario Nov 14 '11 at 23:43
  • why did you wrote `#\b(` and not `#/(` – dynamic Nov 14 '11 at 23:44
  • @yes123: Both would work I believe. The `/` however only if there are preceeding path fragments, like in that exact example. But of course matching `/` and then adding `'/'` again as replacement would be an alternative. – mario Nov 14 '11 at 23:47
2

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
steveo225
  • 11,394
  • 16
  • 62
  • 114