4

I need to check to see if a variable contains anything OTHER than a-z, A-Z, 0-9 and the . character (full stop).

mickmackusa
  • 43,625
  • 12
  • 83
  • 136
zuk1
  • 18,009
  • 21
  • 59
  • 63

4 Answers4

10

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
  • 47,148
  • 35
  • 106
  • 149
8
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
  • 5,755
  • 2
  • 27
  • 20
  • 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 Dec 28 '08 at 14:44
  • 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 Dec 28 '08 at 14:50
8
if (preg_match('/[^A-Z\d.]/i', $var))
  print $var;
PEZ
  • 16,821
  • 7
  • 45
  • 66
0

If you don't want to wheel out the regex engine, you can ltrim the string by the whitelisted characters, then check if the string is empty.

Yes, the trim() functions allow character ranges to be expressed via "yatta-yatta" dots. Read more about it at Native PHP functions that allow double-dot range syntax.

Code: (Demo)

if (ltrim($str, 'A..Za..z0..9.') !== '') {
    // all good
}
mickmackusa
  • 43,625
  • 12
  • 83
  • 136