tags:

views:

95

answers:

2

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? thanks.

+11  A: 
$abcd = str_replace(' ', '', 'this is a test');

See http://de.php.net/manual/en/function.str-replace.php

Gordon
A: 

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

Roland
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.
Savageman
@savageman - str_replace is a better option to use, I posted this as an alternative.
Roland
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.
Syntax Error
@Syntax Error, yip str_replace is faster. Thx for mentioning it.
Roland
Looks like the OP doesn't care about performance though :D
Gordon
overkill. @Gordon's solution is better.
macek