Check if Password is Alphanumeric – PHP

A couple of weeks ago, I spent several hours trying to figure out how to check if a password is alphanumeric or not. Following is a function that worked along with explanation.

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.

Line 4 checks for the presence of an alphabet in the ‘$password1′ string AND also checks for the presence of a digit in ‘$password1′ string. If it finds at least one alphabet and at least one digit, it returns true. Otherwise, it returns false.

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/

Leave a Reply