lisovaccaro
lisovaccaro

Reputation: 33956

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.

Upvotes: 73

Views: 98674

Answers (6)

Damith Ruwan
Damith Ruwan

Reputation: 338

You can use,

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

You can use for unicode characters,

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

Upvotes: 9

John Conde
John Conde

Reputation: 219804

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

Upvotes: 135

Chuck Le Butt
Chuck Le Butt

Reputation: 48758

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

Upvotes: 15

sevenadrian
sevenadrian

Reputation: 416

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!

Upvotes: 20

Alix Axel
Alix Axel

Reputation: 154533

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

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

Upvotes: 3

lisovaccaro
lisovaccaro

Reputation: 33956

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

Seems to work, actually the example was in PHP documentation on preg_replace

Upvotes: 5

Related Questions