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

如果在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,

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.

Because, do you want 3 spaces becoming 2, which is the result of some of the other answers.

I would toss a trim() in to the mix for good measure.

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?

I.e.

 $my_doublespace = preg_replace('/  /', ' ', $my_doublespace);

str_replace function also works fine.

$my_doublespace = str_replace('  ', ' ', $my_doublespace);