How do you replace multiple blank spaces with just 1 blank space


Is there a Php Command or how do you replace multiple blank spaces in a string with just 1 blank space?
For example say the string is:

$string = "Rental Scooter        Florida"

as you can see there are multiple blank spaces between Scooter and Florida.
So is there a function or code you can suggest that one would submit this string to and get:

$string = "Rental Scooter Florida"

with ONLY 1 blank space between each Word of the string.


Cancelling down consecutive white spaces to just one within the string can be done with the following:

preg_replace('# {2,}#', ' ', $str);

If you’d like to specifically replace 2 or more white spaces with one in between words only, then the following should work:

preg_replace('#([a-z0-9\\-]) {2,}([a-z0-9\\-])#i', '\\1 \\2', $str);


Neither of these codes is doing the Job!

It works fine for me…

$str = 'First          Second';
echo "<pre>" . $str . "<br />"; // Outputs "First          Second"
echo preg_replace('# {2,}#', ' ', $str) . "</pre>"; // Outputs "First Second"

Did you forget to put the echo statement in front of preg_replace?

The preg_replace() function does not pass its third argument by reference, so you will need to reassign the $str variable to the returned result of preg_replace():

$str = preg_replace('# {2,}#', ' ', $str); 


I am sorry, you are write, it works fine.
Sorry again and thank you.


Try out this.

You can use preg_replace to replace any sequence of whitespace chars with a dash…

$string = preg_replace(‘/\s+/’, ‘-’, $string);

Hope this helps.