tags:

views:

783

answers:

3

I need to check to see if a variable contains anything OTHER than a-z A-Z 0-9 and the "." character (full stop). Any help would be appreciated.

+3  A: 
if (preg_match("/[^A-Za-z0-9.]/", $myVar)) {
   // make something
}

The key point here is to use "^" in the [] group - it matches every character except the ones inside brackets.

maxnk
I think that this would only detect strings consisting of _only_ the unspecified characters - it might be better to use /[^A-Za-z0-9\.]/
Tom Haigh
Much better. But I still suggest /[^A-Z\d.]/i since it's clearer and less to type. And you don't need to escape the "." inside character classes.
PEZ
+6  A: 
if (preg_match('/[^A-Z\d.]/i', $var))
  print $var;
PEZ
+5  A: 

There are two ways of doing it.

Tell whether the variable contains any one character not in the allowed ranges. This is achieved by using a negative character class [^...]:

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

Th other alternative is to make sure that every character in the string is in the allowed range:

!preg_match('/^[a-zA-Z0-9\.]*$/', $your_variable);
ʞɔıu