Tuesday, March 1, 2011

Allowing Only Certain Characters In PHP

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.

From stackoverflow
  • 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.

    Tom Haigh : I think that this would only detect strings consisting of _only_ the unspecified characters - it might be better to use /[^A-Za-z0-9\.]/
    PEZ : 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.
  • if (preg_match('/[^A-Z\d.]/i', $var))
      print $var;
    
  • 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);
    

0 comments:

Post a Comment