Only allow specific characters in PHP

I need to check if the variable contains ANYTHING other than az AZ 0-9 and ".". symbol (full stop). Any help would be appreciated.

+5
source share
3 answers
if (preg_match('/[^A-Z\d.]/i', $var))
  print $var;
+8
source

There are two ways to do this.

Indicate whether the variable contains any one character, and not in the allowed ranges. This is achieved using the negative character class [^ ...]:

preg_match('/[^a-zA-Z0-9\.]/', $your_variable);

Another alternative is to make sure that each character in the string is in the allowed range:

!preg_match('/^[a-zA-Z0-9\.]*$/', $your_variable);
+9
source
if (preg_match("/[^A-Za-z0-9.]/", $myVar)) {
   // make something
}

"^" [] - , , .

+6

All Articles