71

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.

trejder
  • 17,148
  • 27
  • 124
  • 216
lisovaccaro
  • 32,502
  • 98
  • 258
  • 410
  • 1
    possible duplicate of [How do I remove non alphanumeric characters in a string? (including ß, Ê, etc.)](http://stackoverflow.com/questions/7271607/how-do-i-remove-non-alphanumeric-characters-in-a-string-including-ss-e-etc) – mario Jul 04 '12 at 00:51
  • @mario: That's a bit different since it deals with Unicode. I'm sure a perfect duplicate exists tho... – Alix Axel Jul 04 '12 at 00:57
  • 1
    possible duplicate of [Remove non-alphanumeric characters](http://stackoverflow.com/questions/659025/remove-non-alphanumeric-characters) – trejder Jan 15 '15 at 13:04

6 Answers6

135
$url = preg_replace('/[^\da-z]/i', '', $string);
John Conde
  • 217,595
  • 99
  • 455
  • 496
  • 13
    In case anyone else was momentarily confused by Xeoncross' comment at first glance, his point was that the answer *doesn't* support Unicode characters. But the solution in Xeoncross' link *does*. – orrd Sep 29 '16 at 04:57
20

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!

sevenadrian
  • 416
  • 2
  • 4
14

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

Chuck Le Butt
  • 47,570
  • 62
  • 203
  • 289
9

You can use,

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

You can use for unicode characters,

$url = preg_replace("/[^[:alnum:][:space:]]/u", '', $string);
Damith Ruwan
  • 338
  • 5
  • 18
5
preg_replace('/[\s\W]+/', '', $string)

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

lisovaccaro
  • 32,502
  • 98
  • 258
  • 410
3
$alpha = '0-9a-z'; // what to KEEP
$regex = sprintf('~[^%s]++~i', preg_quote($alpha, '~')); // case insensitive

$string = preg_replace($regex, '', $string);
Alix Axel
  • 151,645
  • 95
  • 393
  • 500