Php - 删除字符串中重复的单词

时间:2012-05-18 15:17:34

标签: php regex string

输入:球球代码

输出应为:球码

输入:awycodeawy

输出应为:awycode

我尝试了这些,但没有奏效:

$q = preg_replace("/\s(\w+\s)\1/i", "$1", $q);
$q = preg_replace("/s(w+s)1/i", "$1", $q);

2 个答案:

答案 0 :(得分:3)

$q = preg_replace("/\b(\w+)\s+\\1\b/i", "$1", $q);

答案 1 :(得分:3)

以下是基于正则表达式解决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'

尽管您可以输入'awycodeawy',但它会转到'codeawy'而不是'awycode'。原因是有可能找到variable length lookahead lookbehind无法实现的内容。

相关问题