4

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?

0

3 Answers 3

16
$abcd = str_replace(' ', '', 'this is a test');

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

Sign up to request clarification or add additional context in comments.

Comments

3

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

5 Comments

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 - str_replace is a better option to use, I posted this as an alternative.
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, yip str_replace is faster. Thx for mentioning it.
overkill. @Gordon's solution is better.
0
$string = preg_replace('/\s+/', '', $string);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.