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

streetparade picture streetparade · Jan 21, 2010 · Viewed 1.2M times · Source

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?

Answer

Mark Byers picture Mark Byers · Jan 21, 2010

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).