Reputation: 804
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');
}
Upvotes: 0
Views: 51
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
Reputation: 2359
str_replace
function also works fine.
$my_doublespace = str_replace(' ', ' ', $my_doublespace);
Upvotes: 2
Reputation: 59997
Why not use preg_replace?
I.e.
$my_doublespace = preg_replace('/ /', ' ', $my_doublespace);
Upvotes: 2