Friday 2 August 2019

How to remove all white spaces within a string using PHP

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.
$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

0 comments:

Post a Comment