正则表达式多余空格怎么去掉?
程序员文章站
2022-04-22 22:01:49
...
echo $keyword = "上海|北京!成都 深圳";echo "
"; $old1 = array("/(\s*)(\s)(\s*)/","/(\s*)(\|)(\s*)/","/(\s*)(!)(\s*)/");$new1 = array('" "','"|"','" "!');echo $keyword3="\"".preg_replace($old1,$new1,$keyword)."\"";//输出:"上海"|"北京" "!成都" "深圳"echo $keyword = "上海 | 北京 !成都 深圳";echo "
"; $old1 = array("/(\s*)(\s)(\s*)/","/(\s*)(\|)(\s*)/","/(\s*)(!)(\s*)/");$new1 = array('" "','"|"','" "!');echo $keyword3="\"".preg_replace($old1,$new1,$keyword)."\"";//输出:"上海" ""|"" "北京" "" "!成都" "深圳"
上面两种情况:第一种是显示是对的,第二种给各符号间加了空格输去就错误了。请问多余的空格怎么屏蔽掉?
回复讨论(解决方案)
没看懂你的需求,我做的话用\S提取就足够了
下面的做法能满足你的需要吗?
echo $keyword = "上海|北京!成都 深圳";echo "
"; $old1 = array("/(\s*)(\s)(\s*)/","/(\s*)(\|)(\s*)/","/(\s*)(!)(\s*)/");$new1 = array('" "','"|"','" "!');echo $keyword3="\"".preg_replace($old1,$new1,$keyword)."\"";//输出:"上海"|"北京" "!成都" "深圳"echo $keyword = "上海 | 北京 !成都 深圳";$keyword = str_replace(" ","",$keyword);echo "
"; $old1 = array("/(\s*)(\s)(\s*)/","/(\s*)(\|)(\s*)/","/(\s*)(!)(\s*)/");$new1 = array('" "','"|"','" "!');echo $keyword3="\"".preg_replace($old1,$new1,$keyword)."\"";//输出:"上海" ""|"" "北京" "" "!成都" "深圳"
下面的做法能满足你的需要吗?
PHP code
?
123456789101112131415
echo $keyword = "上海|北京!成都 深圳"; echo "
"; $old1 = array("/(\s*)(\s)(\s*)/","/(\s*)(\|)(\s*)/","/(\s*)(!)(\s*)/"); $new1 = array('……
还是不行。你的显示是:"上海"|"北京" "!成都深圳"
我想要的结果是:"上海"|"北京" "!成都" "深圳"
没看懂你的需求,我做的话用\S提取就足够了
我的需求是把:"上海|北京!成都 深圳" 变成 "上海"|"北京" "!成都" "深圳"
没看懂你的需求,我做的话用\S提取就足够了
"上海 | 北京 !成都 深圳" 也要变成 "上海"|"北京" "!成都" "深圳"
这样写
$keyword = "上海|北京!成都 深圳"; //输出:"上海"|"北京" "!成都" "深圳"$keyword = "上海 | 北京 !成都 深圳";//输出:"上海"|"北京" "!成都" "深圳"echo "
"; $old1 = array("/!?[^\s!|]+/", "/\s+/", "/\s*\|\s*/", '/""/');$new1 = array('"$0"', ' ', '|', '" "');echo $keyword3 = preg_replace($old1,$new1,$keyword);
参考一下
$old1 = array("/(\s*)(\|)(\s*)/","/(\s*)(!)(\s*)/","/(\s*)(\s)(\s*)(?!\")/");$new1 = array('"|"','" "!','" "');
echo $keyword = "上海 | 北京 !成都 深圳";$keyword = str_replace(" ","",$keyword);echo "
"; $old1 = array("/(\s*)(\|)(\s*)/","/(\s*)(!)(\s*)/","/(\s*?)(\s)(\s*?)/");$new1 = array('"|"','" "!','" "');echo $keyword3="\"".preg_replace($old1,$new1,$keyword)."\"";//输出:"上海" ""|"" "北京" "" "!成都" "深圳"
试试