[英]Php - Remove repeated words in a string
Input: ball ball code 输入:滚珠代码
Output should be: ball code 输出应为:球代码
Input: awycodeawy 输入:awycodeawy
Output should be: awycode 输出应为:awycode
I tried these, but didn't work: 我尝试了这些,但是没有用:
$q = preg_replace("/\s(\w+\s)\1/i", "$1", $q);
$q = preg_replace("/s(w+s)1/i", "$1", $q);
$q = preg_replace("/\b(\w+)\s+\\1\b/i", "$1", $q);
Here is positive lookahead base attempt on regex based solution to OP's problem. 这是基于正则表达式的解决OP问题的积极前瞻性尝试。
$arr = array('ball ball code', 'abcabc bde bde', 'awycodeawy');
foreach($arr as $str)
echo "'$str' => '" . preg_replace('/(\w{2,})(?=.*?\\1)\W*/', '', $str) ."'\n";
'ball ball code' => 'ball code'
'abcabc bde bde' => 'abc bde'
'awycodeawy' => 'codeawy'
As you can for the input 'awycodeawy'
it makes it to 'codeawy'
instead of 'awycode'
. 您可以为输入'awycodeawy'
为'codeawy'
而不是'awycode'
。 The reason is that it is possible to find a variable length lookahead
something which is not possible for lookbehind
. 原因是有可能找到一个variable length lookahead
而这对于后lookbehind
对象是不可能的。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.