正则表达式多余空格怎么去掉?

WBOY
Release: 2016-06-23 14:05:08
Original
1224 people have browsed it

echo $keyword = "上海|北京!成都 深圳";echo "<br />"; $old1 = array("/(\s*)(\s)(\s*)/","/(\s*)(\|)(\s*)/","/(\s*)(!)(\s*)/");$new1 = array('" "','"|"','" "!');echo $keyword3="\"".preg_replace($old1,$new1,$keyword)."\"";//输出:"上海"|"北京" "!成都" "深圳"echo $keyword = "上海 | 北京 !成都   深圳";echo "<br />"; $old1 = array("/(\s*)(\s)(\s*)/","/(\s*)(\|)(\s*)/","/(\s*)(!)(\s*)/");$new1 = array('" "','"|"','" "!');echo $keyword3="\"".preg_replace($old1,$new1,$keyword)."\"";//输出:"上海" ""|"" "北京" "" "!成都" "深圳"
Copy after login

上面两种情况:第一种是显示是对的,第二种给各符号间加了空格输去就错误了。请问多余的空格怎么屏蔽掉?


回复讨论(解决方案)

没看懂你的需求,我做的话用\S提取就足够了

下面的做法能满足你的需要吗?

echo $keyword = "上海|北京!成都 深圳";echo "<br />"; $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 "<br />"; $old1 = array("/(\s*)(\s)(\s*)/","/(\s*)(\|)(\s*)/","/(\s*)(!)(\s*)/");$new1 = array('" "','"|"','" "!');echo $keyword3="\"".preg_replace($old1,$new1,$keyword)."\"";//输出:"上海" ""|"" "北京" "" "!成都" "深圳"
Copy after login

下面的做法能满足你的需要吗?



PHP code
?



123456789101112131415

echo $keyword = "上海|北京!成都 深圳"; echo "
"; $old1 = array("/(\s*)(\s)(\s*)/","/(\s*)(\|)(\s*)/","/(\s*)(!)(\s*)/"); $new1 = array('……
还是不行。你的显示是:"上海"|"北京" "!成都深圳"
我想要的结果是:"上海"|"北京" "!成都" "深圳"

没看懂你的需求,我做的话用\S提取就足够了
我的需求是把:"上海|北京!成都 深圳" 变成 "上海"|"北京" "!成都" "深圳"

没看懂你的需求,我做的话用\S提取就足够了

"上海 | 北京 !成都 深圳" 也要变成 "上海"|"北京" "!成都" "深圳"

这样写

$keyword = "上海|北京!成都 深圳";     //输出:"上海"|"北京" "!成都" "深圳"$keyword = "上海 | 北京 !成都   深圳";//输出:"上海"|"北京" "!成都" "深圳"echo "<br />"; $old1 = array("/!?[^\s!|]+/", "/\s+/", "/\s*\|\s*/", '/""/');$new1 = array('"$0"', ' ', '|', '" "');echo $keyword3 = preg_replace($old1,$new1,$keyword);
Copy after login

参考一下

$old1 = array("/(\s*)(\|)(\s*)/","/(\s*)(!)(\s*)/","/(\s*)(\s)(\s*)(?!\")/");$new1 = array('"|"','" "!','" "');
Copy after login

echo $keyword = "上海 | 北京 !成都   深圳";$keyword = str_replace(" ","",$keyword);echo "<br />"; $old1 = array("/(\s*)(\|)(\s*)/","/(\s*)(!)(\s*)/","/(\s*?)(\s)(\s*?)/");$new1 = array('"|"','" "!','" "');echo $keyword3="\"".preg_replace($old1,$new1,$keyword)."\"";//输出:"上海" ""|"" "北京" "" "!成都" "深圳"
Copy after login

试试

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template