【发布时间】:2019-11-29 21:15:18
【问题描述】:
我想从字符串中删除重复的单词(只有连续的)。
$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
【问题讨论】:
标签: php regex preg-replace