Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

preg_replace in PHP - regular expression for NOT condition

I am trying to write a function in PHP using preg_replace where it will replace all those characters which are NOT found in list. Normally we replace where they are found but this one is different.

For example if I have the string:

$mystring = "ab2c4d";

I can write the following function which will replace all numbers with *:

preg_replace("/(\d+)/","*",$mystring);

But I want to replace those characters which are neither number nor alphabets from a to z. They could be anything like #$*();~!{}[]|\/.,<>?' e.t.c.

So anything other than numbers and alphabets should be replaced by something else. How do I do that?

Thanks

like image 637
Ali Avatar asked Jan 18 '11 13:01

Ali


1 Answers

You can use a negated character class (using ^ at the beginning of the class):

/[^\da-z]+/i

Update: I mean, you have to use a negated character class and you can use the one I provided but there are others as well ;)

like image 125
Felix Kling Avatar answered Nov 15 '22 16:11

Felix Kling