简体   繁体   English

如果在php的字符串之间发现两个空格,如何删除一个空格?

[英]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 want the result like this "Marketing and Sales Staff", only one white space between "Marketing" and "and". 我想要这样的结果“营销和销售人员”,“营销”和“与”之间只有一个空格。 Is there anyway to remove it? 反正有删除它吗?

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);

You can try this live here 你可以在这里尝试

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM