PHP: Removing whitespace characters.

This is a short guide on how to remove whitespace characters in PHP. In some cases, this is necessary if you are dealing with external data from users, files or other websites. Examples include telephone numbers, vehicle registration numbers and post codes.

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

Removing spaces.

If you want to remove spaces from a string, you can use PHP’s native str_replace function like so:

//Example string.
$string = ' 12 WD2039 ';

//Remove all spaces from the string
//using str_replace.
$string = str_replace(' ', '', $string);

//var_dump the new string.
var_dump($string);

If you run the code snippet above, you will see that we are left with: 12WD2039.

This is because we told the str_replace function to replace all space characters in our string with nothing.

However, this approach will not work with ‘special’ whitespace characters such as the “new line”.

Remove ALL whitespace characters.

If you need to remove ALL whitespace characters, then you can use the preg_replace function. This may be necessary if you encounter data that contains tabbed spaces or invisible end line characters.

With PHP’s preg_replace function, we can use regular expressions to search for and replace all whitespace characters:

//Example string containing a newline character
//and a tab character.
$string = " 12\nWD2039\t";

//Remove ALL whitespace characters.
$string = preg_replace('/\s+/', '', $string);

//var_dump the clean string.
var_dump($string);

If you run the PHP above, you’ll see that our regular expression removed the offending characters. If you replace the preg_replace line with the str_replace solution that we used in the first example, you will see that it only strips out the first character.

Remove spaces from the beginning and end of a string.

Sometimes, you might only want to remove spaces from the beginning and end of a string. In that case, the trim function is your best friend:

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

//Trim the string.
$string = trim($string);

//var_dump the clean string.
var_dump($string);

It is worth pointing out that the trim function will remove all whitespace characters, not just regular spaces. i.e. It will also take care of those annoying “end lines” and “carriage returns”.

Hopefully, you found this guide useful!