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