I’m using perl flavored regexes in PHP with the preg_match function. I want to validate a key that is exactly 10 characters, with upper case alpha characters or numbers.
I have
preg_match( '/[^A-Z0-9]/', $key);
which finds invalid characters next to valid ones. In my limited knowledge, I tried
preg_match( '/[^A-Z0-9]{10}$/', $key);
which turns out to match all my test strings, even the invalid ones.
How do I specify this regular expression?
You’ve misplaced the
^character which anchors the beginning of a string./[^A-Z0-9]{10}$/would match all files ending on 10 characters that are not uppercase letters and digits.The correct RE would be:
Explanation of the regexp:
^– matches from the beginning of the string[– begin of a character class, a character should match against these. If a^is found straight after this[, it negates the matchA-Z– uppercase letters0-9– digits]– end of a character class{10}– matches the previous character class 10 times$– matches the string till the end