Last Updated:

Removing extra spaces in PHP

Basically, any data that needs to be cleaned up before you can continue processing it will do.

Remove spaces

If you want to remove spaces from a string, you can use PHPstr_replace's own function as follows:

An example of a string.
$string = ‘ 12 WD2039 ‘;
//Remove all spaces from the //use str_replace string
.
$string = str_replace(‘ ‘, «, $string);
//var_dumpthe new string.
Var_dump($string);

If you run the above code snippet, you'll see what we have left: 12WD2039. This is because we told the function str_replace replace all spaces in our string with nothing.
However, this approach will not work with "special" spaces, such as "new line".

Remove all spaces

If you need to remove ALL spaces, then you can use the preg_replace function. This may be necessary if you encounter data that contains whitespace with tabs or invisible characters of the final string.

With the preg_replacePHP function, we can use regular expressions to find and replace all spaces:

An example of a string that contains a newline
character // and a tab character.
$string = » 12\nWD2039\t»;

Remove ALL spaces.
$string = preg_replace(‘/\s+/’, «, $string);

var_dump a blank string.
nesting ($string);

If you run PHP above, you'll see that our regular expression has removed the offensive characters. If you replace the string preg_replace with the str_replace solution we used in the first example, you'll see that it only removes the first character.

Remove spaces from the beginning and end of a line

Sometimes you can just remove spaces from the beginning and end of a line. In this case, the cropping feature is your best friend:

PHP string with unwanted spaces
//at the beginning and at the end.
$string = » 12WD2039 \t\r»;

Crop the line.
$string = trim($string);

var_dump a blank string.
Var_dump($string);

It is worth noting that the trim function will remove all spaces, not just ordinary spaces. It will also take care of those annoying "end lines" and "carriage returns".