Is there php function to remove the space inside the string? for example:
$abcd="this is a test"
I want to get the string:
$abcd="thisisatest"
How to do that?
asked Apr 19, 2010 at 18:11
Jorge
5,68618 gold badges52 silver badges68 bronze badges
3 Answers 3
$abcd = str_replace(' ', '', 'this is a test');
answered Apr 19, 2010 at 18:11
Gordon
318k76 gold badges548 silver badges566 bronze badges
Sign up to request clarification or add additional context in comments.
Comments
The following will also work
$abcd="this is a test";
$abcd = preg_replace('/( *)/', '', $abcd);
echo $abcd."\n"; //Will output 'thisisatest';
or
$abcd = preg_replace('/\s/', '', $abcd);
See manual http://php.net/manual/en/function.preg-replace.php
answered Apr 19, 2010 at 18:27
Elitmiar
37.3k77 gold badges183 silver badges234 bronze badges
5 Comments
Savageman
There is no need to use a regular expression if he only wants to replaces spaces. It can be useful to replace all "spacing" characters with the \s assertion though.
Elitmiar
@savageman - str_replace is a better option to use, I posted this as an alternative.
Syntax Error
Since nobody else said it, I'll go ahead and mention that str_replace is faster than preg_replace. That plus simplicity of use is why it's a preferred alternative. Did not know about \s so thanks for that.
Elitmiar
@Syntax Error, yip str_replace is faster. Thx for mentioning it.
maček
overkill. @Gordon's solution is better.
$string = preg_replace('/\s+/', '', $string);
answered Dec 20, 2013 at 18:58
Fury
4,7867 gold badges54 silver badges83 bronze badges
Comments
lang-php