Check if Password is Alphanumeric – PHP
1 function checkPasswordIsAlphaNumeric($password1){
2 $pattern1 = “/[a-zA-Z]+/”;
3 $pattern2 = “/[0-9]+/”;
4 return ((preg_match($pattern1, $password1)) && (preg_match($pattern2, $password1)));
5 }
Line 1 is simple. We declare a function ‘checkPasswordIsAlphaNumeric’ which takes one argument, password1.
Let’s tease apart the pattern defined in line 2:
- the expression should be enclosed in the delimiters. A common delimiter is forward slash.
- square brackets are used to match a set of characters, also called character class. Any one of the characters inside the square brackets is matched.
- a-zA-Z matches a through z (lower case) or A through Z (upper case)
- + matches one or more of the preceeding pattern
Putting it all together, /[a-zA-Z]+/ matches one or more characters from a through z OR A through Z.
Line 3 is similar to line 2. It matches one or more characters in the range 0 to 9.
Following are some references that helped me decode regular expressions:
http://java.sun.com/docs/books/tutorial/essential/regex/char_classes.html
http://www.webcheatsheet.com/php/regular_expressions.php
http://www.phphacks.com/content/view/31/33/