Back To Normal
Click Here To Subscribe Via Email

Subscribe To Our E-Mail Newsletter

Friday, March 20, 2015

Replacing Multiple Spaces with a Single Space using PHP

Couch ModePrint It

This is just a tiny code snippet that I decided to share (may be someone will get help). This is really simple. It just finds and replaces multiple spaces (white-spaces) with a single space.

PHP Code

$rawName="This            is              my          name     \r\n \r\n";

/* replace spaces. not any newline */
$name = preg_replace("/ {2,}/", ' ', $rawName);

echo $name;

Keep in mind that it will not replace newlines. For replacing spaces, tabs and newlines, you will use something like this

$string="Any string          with spaces \r\n newlines and tabs  ";
$output = preg_replace('/\s+/', ' ', $string);
echo $output;

Have fun coding!