Remove all non-alphanumeric characters using preg_replace

PhpRegexPreg Replace

Php Problem Overview


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.

Php Solutions


Solution 1 - Php

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

Solution 2 - Php

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!

Solution 3 - Php

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

Solution 4 - Php

You can use,

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

You can use for unicode characters,

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

Solution 5 - Php

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

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

Solution 6 - Php

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

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionlisovaccaroView Question on Stackoverflow
Solution 1 - PhpJohn CondeView Answer on Stackoverflow
Solution 2 - PhpsevenadrianView Answer on Stackoverflow
Solution 3 - PhpChuck Le ButtView Answer on Stackoverflow
Solution 4 - PhpDamith RuwanView Answer on Stackoverflow
Solution 5 - PhplisovaccaroView Answer on Stackoverflow
Solution 6 - PhpAlix AxelView Answer on Stackoverflow