Q . preg_replace in PHP - regular expression for NOT condition.

Richa ojha. asked, Jul 19 ' 2016

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 *:


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?

  • PHP
  • regex
  • preg-replace

1 Answers

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


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

Leave a Ansewer