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

April 11, 2010

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

$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);

Profile picture

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

© 2024, withdave.