[英]How to remove one white space if two white space found between string in php?
I want to remove one white space if found two white space between phrase in php, I can detect if there is two white space or not, but I can not remove white space, here is how I tried, 如果要在php中的词组之间找到两个空格,我想删除一个空格,我可以检测是否存在两个空格,但是我无法删除空格,这是我尝试的方法,
my_doublespace = "Marketing and Sales Staff"; if(strpos($my_doublespace, ' ') > 0){ dd('including double space'); } else{ dd('no double'); }
I would do this 我会这样做
$str = preg_replace('/\s{2,}/', ' ', $str);
This will change 2 or more spaces to a single space. 这会将2个或更多的空间更改为一个空间。
Because, do you want 3 spaces becoming 2, which is the result of some of the other answers. 因为,您是否希望3个空格变为2,这是其他一些答案的结果。
I would toss a trim()
in to the mix for good measure. 我会把
trim()
丢进去,以备不时之需。
You can "roll" your own trim like this: 您可以像这样“滚动”自己的修剪:
$str = preg_replace(['/\s{2,}/','/^\s+|\s+$/'],[' ',''], $str);
Why not use preg_replace ? 为什么不使用preg_replace呢?
Ie 即
$my_doublespace = preg_replace('/ /', ' ', $my_doublespace);
str_replace
函数也可以正常工作。
$my_doublespace = str_replace(' ', ' ', $my_doublespace);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.