How to remove all white spaces within a string using PHP

No Comments

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

Image Credits: Photo by Isis França on Unsplash.

Related Articles

No results found

Leave a Reply

avatar
  Subscribe  
Notify of
Menu
Copy link