How to remove all white spaces within a string using PHP?
|
|
|
|
|
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
|