Remove whitespace (spaces) from a string with PHP and preg_replace

Seeing as ereg_replace and that whole family has been depreciated in the newer PHP releases it’s surprising how many sites still show and use it.

This simple function strips out whitespace from a string. Could be useful in taking spaces out of usernames, id’s, who knows.

<?php
$string = 'us er na  me';
$string = nowhitespace($string);
function nowhitespace($data) {
return preg_replace('/\s/', '', $data);
}
// This will be 'username' now
echo $string;
?>

You could use this to make all whitespace only 1 space wide by changing the ” in the following line.

return preg_replace('/\s/', ' ', $data);

Last example modified from the PHP manual.