The following seems to be what you need in this case:
function isValid($str) {
return !preg_match('/[^A-Za-z0-9]/', $str);
}
The […]
regex construct is called a character class. Something like [aeiou]
matches one of any of the vowels.
The [^…]
is a negated character class, so [^aeiou]
matches one of anything but the vowels (which includes consonants, digits, symbols, etc).
The -
, depending on where/how it appears in a character class definition, is a range definition, so 0-9
is the same as 0123456789
.
Thus, the regex [^A-Za-z0-9]
actually matches a character that's neither a letter nor a digit. This is why the result of preg_match
is negated with !
.
That is, the logic of the above method uses double negation:
isValid = it's not the case that
there's something other than a letter or a digit
anywhere in the string
You can alternatively get rid of the double negation and use something like this:
function isValid($str) {
return preg_match('/^[A-Za-z0-9]*$/', $str);
}
Now there's no negation. The ^
and $
are the beginning and of the string anchors, and *
is a zero-or-one-of repetition metacharacter. Now the logic is simply:
isValid = the entire string from beginning to end
is a sequence of letters and digits
References
Related questions
Non-regex alternative
Some languages have standard functions/idiomatic ways to validate that a string consists of only alphanumeric characters (among other possible string "types").
In PHP, for example, you can use ctype_alnum
.
bool ctype_alnum ( string $text )
Checks if all of the characters in the provided string , text
, are alphanumeric.
API links
- PHP Ctype Functions - list of entire family of
ctype
functions
ctype_alpha
, digit
, lower
, upper
, space
, etc