我想从字符串中删除重复的单词(仅连续的)。
$str = 'abc,def,fgh,fgh,xna,fgh,xyz,xyz,xyz,tr,tr,xna';
Run Code Online (Sandbox Code Playgroud)
我想要的输出字符串是:
abc,def,fgh,xna,fgh,xyz,tr,xna
Run Code Online (Sandbox Code Playgroud)
我可以使用以下方法在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);
Run Code Online (Sandbox Code Playgroud)
但是一直在寻找正则表达式方法。到目前为止,我已经熟悉了这两个正则表达式:
$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
Run Code Online (Sandbox Code Playgroud) 我想使用正则表达式从字符串中提取 8 位数字。
测试字符串是
hi 82799162,236232 (82342450),test data 8979
所需的相应输出应为
82799162,82342450,null
我试过以下代码:
preg_match('/[0-9]{8}$/', $string, $match);preg_match('/\d{8}$/', $string, $match);但它不会从 中检索号码236232 (82342450)。