views:

288

answers:

4

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

Say i have a string like $string = "this is my string"; the output should be like "thisismystring"

How can i do that?

+5  A: 

Do you just mean spaces or all whitespace?

For just spaces, use str_replace:

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

For all whitespace, use preg_replace:

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

(From here).

Mark Byers
whitespaces is what i want to remove
streetparade
Thanks this worked for me
streetparade
+2  A: 

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

Arkaaito
»If you don't need fancy replacing rules (like regular expressions), you should always use this function [`str_replace`] instead of `ereg_replace()` or `preg_replace()`.«
Joey
I would not suggest using regular expressions for simple space removal. str_replace for just spaces, preg_replace for all whitespace.
Peter Perháč
GreenMatt
Good point, Johannes. I went for preg_replace() because I misread the question, and thought what he meant was whitespace generally (not necessarily the specific space character).
Arkaaito
Regex?? Realllyyyyyyyyyy...........
AntonioCS
\s\s+ should match only 2 or more whitespace characters, so I don't think this will remove all whitespace.
Mark Byers
Hopelessly broken this one, will remove 2 or more whitespaces, not single, as requested in the example.
ChaosR
+1  A: 

str_replace will do the trick thusly

$new_str = str_replace(' ', '', $old_str);
David Heggie
+1  A: 

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);
codaddict