我想从字符串中删除重复的词(仅连续的)。
$str = 'abc,def,fgh,fgh,xna,fgh,xyz,xyz,xyz,tr,tr,xna';
我期望的输出字符串是:
abc,def,fgh,xna,fgh,xyz,tr,xna
我可以使用以下代码在php中获得我想要的结果:
$ip = explode(',', $str);
$op = [];$last = null;
for($i=0;$i<count($ip);$i++){
if ($last == $ip[$i]) {
continue;
}
$op[]=$last=$ip[$i];
}
$ip = implode(',', $op);
但我希望使用正则表达式的方法。到目前为止,我已经用这两个正则表达式接近了:
$after = preg_replace('/(?:^|,)([^,]+)(?=.*,\1(?:,|$))/m', '', $str);
output : abc,def,fgh,xyz,tr,xna
$after = preg_replace('/([^,]+)(,[ ]*\1)+/m', '', $str);
output : abc,degh,fgh,xna,fgh,,,xna