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?

Dharman
34k27 gold badges105 silver badges156 bronze badges
asked Apr 19, 2010 at 18:11
0

3 Answers 3

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

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

answered Apr 19, 2010 at 18:11
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

answered Apr 19, 2010 at 18:27

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);
answered Dec 20, 2013 at 18:58

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

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.