Home PHP How to remove all white spaces within a string using PHP?
 
 
 

How to remove all white spaces within a string using PHP?

PDF Print E-mail

Question: How to remove all white spaces within a string using PHP?

 

Answer:

There are two functions that could be used namely str_replace and  preg_replace.

First we'll give an example using str_replace. str_replace is the preferred method since it's faster and easier to use than preg_replace which relies on regular expressions.

str_replace (PHP 4, PHP 5) - http://de.php.net/manual/en/function.str-replace.php

 
$string =  "This is a test string";
$new_string = str_replace(' ','',$string);
echo $new_string; //This will output Thisisateststring
 

preg_replace (PHP 4, PHP 5) - http://php.net/manual/en/function.preg-replace.php

 
$string =  "This is a test string";
$new_string = preg_replace('/( *)/','',$string);
echo $new_string; //This will output Thisisateststring
 

or

 
 $string =  "This is a test string";
 $new_string = preg_replace('/\s/','',$string); // \s means strip all white spaces
 echo $new_string; //This will output Thisisateststring
 

+/-
+/- Write comment
Your Contact Details:
Comment:
[b] [i] [u] [url] [quote] [code] [img]   
:angry::0:confused::cheer:B):evil::silly::dry::lol::kiss::D:pinch:
:(:shock::X:side::):P:unsure::woohoo::huh::whistle:;):s
:!::?::idea::arrow:
Security Please input the anti-spam code that you can read in the image.
 

Go Daddy $7.49 .com Sale!