简体   繁体   English

删除字符串PHP中最后一个重复出现的单词

[英]Remove last repeated word occurence in a string PHP

I need remove last repeated word in a string, example: 我需要删除字符串中最后一个重复的单词,例如:

Last repeat word is: all/ 最后一个重复的单词是: 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/ 结果应始终为: item1/item2/

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: 或者,如果all是要查找的固定字符串:

$str = preg_replace('#/(all/)+$#', '/', $str);

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM