Remove all non-alphanumeric characters using preg_replace

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.

+50
php regex preg-replace
Jul 04 2018-12-12T00:
source share
6 answers
 $url = preg_replace('/[^\da-z]/i', '', $string); 
+99
Jul 04 2018-12-12T00:
source share

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!

+13
Jul 04 '12 at 1:27
source share

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

+12
Jul 30 '13 at 13:05
source share
 preg_replace('/[\s\W]+/', '', $string) 

It seems to work, in fact the example was in the PHP documentation on preg_replace

+4
Jul 04 2018-12-12T00: 00Z
source share
 $alpha = '0-9a-z'; // what to KEEP $regex = sprintf('~[^%s]++~i', preg_quote($alpha, '~')); // case insensitive $string = preg_replace($regex, '', $string); 
+3
Jul 04 2018-12-12T00:
source share

you can use

 $url = preg_replace('/[^\da-z]/i', '', $string); 

You can use Unicode characters,

 $url = preg_replace("/[^[:alnum:][:space:]]/u", '', $string); 
+1
Jun 26 '17 at 7:31 on
source share



All Articles