preg_replace in PHP - regular expression for NOT condition

Ali picture Ali · Jan 18, 2011 · Viewed 36.7k times · Source

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

Answer

Felix Kling picture Felix Kling · Jan 18, 2011

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 ;)