Hướng dẫn trim space php

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?

Hướng dẫn trim space php

asked Jan 21, 2010 at 13:02

streetparadestreetparade

31k36 gold badges99 silver badges122 bronze badges

4

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

PaulH

2,8021 gold badge14 silver badges30 bronze badges

answered Jan 21, 2010 at 13:04

Mark ByersMark Byers

778k181 gold badges1551 silver badges1440 bronze badges

11

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

answered Jan 21, 2010 at 13:05

8

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

answered Jan 21, 2010 at 13:05

codaddictcodaddict

434k80 gold badges487 silver badges524 bronze badges

1

str_replace will do the trick thusly

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

answered Jan 21, 2010 at 13:05

Hướng dẫn trim space php

David HeggieDavid Heggie

2,8481 gold badge24 silver badges21 bronze badges

1

Not the answer you're looking for? Browse other questions tagged php string spaces or ask your own question.