How do I strip all spaces out of a string in PHP?

PhpStringSpaces

Php Problem Overview


How can I strip / remove all spaces of a string in PHP?

I have a string like $string = "this is my string";

The output should be "thisismystring"

How can I do that?

Php Solutions


Solution 1 - Php

Do you just mean spaces or all whitespace?

For just spaces, use str_replace:

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

For all whitespace (including tabs and line ends), use preg_replace:

$string = preg_replace('/\s+/', '', $string);

(From here).

Solution 2 - Php

If you want to remove all whitespace:

$str = preg_replace('/\s+/', '', $str);

See the 5th example on the preg_replace documentation. (Note I originally copied that here.)

Edit: commenters pointed out, and are correct, that str_replace is better than preg_replace if you really just want to remove the space character. The reason to use preg_replace would be to remove all whitespace (including tabs, etc.).

Solution 3 - Php

If you know the white space is only due to spaces, you can use:

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

But if it could be due to space, tab...you can use:

$string = preg_replace('/\s+/','',$string);

Solution 4 - Php

str_replace will do the trick thusly

$new_str = str_replace(' ', '', $old_str);

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionstreetparadeView Question on Stackoverflow
Solution 1 - PhpMark ByersView Answer on Stackoverflow
Solution 2 - PhpArkaaitoView Answer on Stackoverflow
Solution 3 - PhpcodaddictView Answer on Stackoverflow
Solution 4 - PhpDavid HeggieView Answer on Stackoverflow