How to remove all non-alphanumeric characters from a string in PHP?
This is the code I'm currently using:
$url = preg_replace('/\s+/', '', $string);
It replaces only spaces.
$url = preg_replace('/[^\da-z]/i', '', $string);
Take it first, how would I do it
$str = 'qwerty!@#$@#$^@#$Hello%#$'; $outcome = preg_replace("/[^a-zA-Z0-9]/", "", $str); var_dump($outcome); //string(11) "qwertyHello"
Hope this helps!
Not sure why no one else suggested this, but this seems to be the simplest regular expression:
preg_replace("/\W|_/", "", $string)
You can also see this in action: http://phpfiddle.org/lite/code/0sg-314
preg_replace('/[\s\W]+/', '', $string)
It seems to work, in fact the example was in the PHP documentation on preg_replace
$alpha = '0-9a-z'; // what to KEEP $regex = sprintf('~[^%s]++~i', preg_quote($alpha, '~')); // case insensitive $string = preg_replace($regex, '', $string);
you can use
You can use Unicode characters,
$url = preg_replace("/[^[:alnum:][:space:]]/u", '', $string);