I need a regular expression that will allow only a to z and 0 to 9. I came across the function below on this site, but it allows a few symbols thru (#.-). How should it be done if it has to allow only a to z (both upper and lower case) and 0 to 9? I’m scared to edit it since I know nothing about regular expressions.
Also is this regular expression good to check for a to z and 0 to 9, or is there any way it can be bettered.
function isValid($str) {
return !preg_match('/[^A-Za-z0-9.#\\-$]/', $str);
}
Thanks
The following seems to be what you need in this case:
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, so0-9is the same as0123456789.Thus, the regex
[^A-Za-z0-9]actually matches a character that’s neither a letter nor a digit. This is why the result ofpreg_matchis negated with!.That is, the logic of the above method uses double negation:
You can alternatively get rid of the double negation and use something like this:
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: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.API links
ctypefunctionsctype_alpha,digit,lower,upper,space, etc