Stripping everything but letters and numbers from a string in PHP with preg_replace

Useful for a number of things including username and anything else you don’t want ANY special chars in, leaving only alphanumeric digits.

<?php
$string = 'us$$er*&^nam@@e';
$string = cleanabc123($string);
function cleanabc123($data)
{
$data = preg_replace("/[^a-zA-Z0-9\s]/", "", $data);
return $data;
}
// This will be 'username' now
echo $string;
?>

And if you wanted it to also remove whitespace, you could change the function by removing the \s whitespace character.

$data = preg_replace("/[^a-zA-Z0-9]/", "", $data);

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.