PHP function that strips all non alphanumeric characters
Sometimes it’s necessary to only return alphanumeric characters in a PHP script.
Whether you’re trying to upload images and get a uniform name for your image, or you just need to get a key you can hash with an obvious solid value then this function is for you. This function is the fastest, most reliable way I know of to return just alphanumeric characters in PHP.
The function
// GET ALPHANUMERIC
function return_alphanumeric($string) {
return preg_replace('#\W#', '', $string);
}
Oh boy,
Bryan
Related reading
2 Responses to “PHP function that strips all non alphanumeric characters”
Leave a Reply

Carsten on October 7th, 2009
\w and \W depend on the locale being used. This means that, for instance, with a German locale setting the code above will not remove ä ö ü Ä Ö Ü ß
Apart from that, \w always includes the underscore, which is not an alphanumeric.
preg_replace(’#[^a-z0-9]#i’, ”, $string) will do the job.
Garrett on December 9th, 2009
Any idea which is faster?
preg_replace(’#[^a-z0-9]#i’, ”, $string)
or
preg_replace(’#[^a-z0-9A-Z]#’, ”, $string)
or do they compile down to the same regex and are equivalent?
Any slight improvement would make a huge difference in my script, as I’m running around 100 million replaces total.