简体   繁体   中英

Remove all non-alphanumeric characters using preg_replace

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.

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

At first take this is how I'd 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 has suggested this, but this seems to be the simplest regex:

preg_replace("/\W|_/", "", $string)

You can see it in action here, too: http://phpfiddle.org/lite/code/0sg-314

preg_replace('/[\s\W]+/', '', $string)

似乎工作,实际上这个例子是在preg_replace上的PHP文档中

$alpha = '0-9a-z'; // what to KEEP
$regex = sprintf('~[^%s]++~i', preg_quote($alpha, '~')); // case insensitive

$string = preg_replace($regex, '', $string);

You can use,

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

You can use for unicode characters,

$url = preg_replace("/[^[:alnum:][:space:]]/u", '', $string);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM