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

April 04, 2010

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, etc.

$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.

Profile picture

From Dave, who writes to learn things. Thoughts and views are his own.

© 2024, withdave.