PHP

How to remove all white spaces within a string using PHP

Written by Ian Carnaghan · 30 sec read >

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

Last Updated On March 22, 2018
Written by Ian Carnaghan
I am a software developer and online educator who likes to keep up with all the latest in technology. I also manage cloud infrastructure, continuous monitoring, DevOps processes, security, and continuous integration and deployment. Profile

Leave a Reply

avatar
  Subscribe  
Notify of