Soul Coder
Soul Coder

Reputation: 804

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,

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?

Upvotes: 0

Views: 51

Answers (3)

ArtisticPhoenix
ArtisticPhoenix

Reputation: 21661

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

Upvotes: 3

Md Mahfuzur Rahman
Md Mahfuzur Rahman

Reputation: 2359

str_replace function also works fine.

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

Upvotes: 2

Ed Heal
Ed Heal

Reputation: 59997

Why not use preg_replace?

I.e.

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

Upvotes: 2

Related Questions