-2

Possible Duplicate:
Regex to match mixed case words

Hello I'm working on a class project for a CIS Class. I need help writing a regular expression that can check a password. The requirements for the password is it must be 8 characters long and must contain one upper and one lowercase letter and at least one number. Thanks for the help. Example: Pasword1

heres what I have so far [a-zA-Z0-9]{8}

bitsapien
  • 1,753
  • 12
  • 24
mvmrocks
  • 85
  • 2
  • 11
  • 4
    Paste what you have done so far, so people can help you on your own snippet – Daryl Gill Dec 05 '12 at 00:05
  • 1
    Lookaheads will be of big help, if you're allowed to use them. – Amadan Dec 05 '12 at 00:06
  • What I would suggest is exploding the password, sorting the elements of the resulting array and imploding them back together. Then work on a regex that will satisfy your constraints knowing the characters in a sorted order. – sberry Dec 05 '12 at 00:08
  • @sberry I'm pretty sure using `explode();` and `implode();` is adding extra efforts; there's already functions to search for capital letters, symbols and information on the strings length – Daryl Gill Dec 05 '12 at 00:09
  • /^[a-zA-Z0-9]{8}$/ should work better to validate only passwords containing 8 alphanums – SmasherHell Dec 05 '12 at 00:13

2 Answers2

1

This should do what you need:

$password = "Pasword1";
$pattern = '/^(?=.*\d)(?=.*[A-Z]).{8,}$/';
if(preg_match($pattern, $password))
{
    echo "Good password!";
}
else
{
    echo "Bad password";
}
Chris
  • 111
  • 5
  • only problem is stuff like this "password" works. I need it to have 8 characters at least one upper case and one lower case and at least 1 number. Example: Pasword1 – mvmrocks Dec 05 '12 at 03:17
  • @mvmrocks: Did you try it? Because [looks all right to me](http://rubular.com/r/0OGlnfzNqO). The only possible problem is if you want to disallow 9-or-more-character passwords, in which case you just drop the comma near the end. – Amadan Dec 05 '12 at 07:23
0

You need to do positive lookahead (?=(regex)) in order to do this. If you need exactly 8 characters and you are allowed any type of characters other than need 1 each of digit, upper and lower case letter, then you can use this:

$pattern = '/^(?=.*[0-9])(?=.*[A-Z])(?=.*[a-z]).{8}$/';

If you need 8 or more characters than simply modify to this:

$pattern = '/^(?=.*[0-9])(?=.*[A-Z])(?=.*[a-z]).{8,}$/'; 
Mike Brant
  • 70,514
  • 10
  • 99
  • 103