Remove all non-alphanumeric characters using preg_replace

lisovaccaro picture lisovaccaro · Jul 4, 2012 · Viewed 87k times · Source

How can I remove all non alphanumeric characters from a string in PHP?

This is the code, that I'm currently using:

$url = preg_replace('/\s+/', '', $string);

It only replaces blank spaces.

Answer

John Conde picture John Conde · Jul 4, 2012
$url = preg_replace('/[^\da-z]/i', '', $string);