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
2008-12-28 13:53:13
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
2008-12-28 14:44:49
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
2008-12-28 14:50:05
+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
2008-12-28 14:52:31