Jump to content

PREG_MATCH: alphanumeric, length, char check in one statement


xProteuSx

Recommended Posts

I'm creating a registration, and need users to add a password that is alphanumeric, 8-20 characters in length, and contains at least one number and one letter.  I got this to work:

 

if ((!ereg("^([a-zA-Z0-9]){8,20}$", $_POST['password'])) || (!preg_match("#^.*(?=.*\d)(?=.*[a-z]).*$#i", $_POST['password'])))

  { $error = true; }

 

However, I am wondering if I can do this with a single preg_match statement.

 

This complex ereg and preg_match stuff makes me light headed ...

 

I haven't been able to find a similar example anywhere.  Thanks in advance.

Of course you can.

 

/^(?=[a-zA-Z0-9]{8,20}$)(?=.*?\d)(?=.*?[a-zA-Z])/

 

This approach uses "look aheads" (?=...) anchored at the start of the string which might look a bit odd at first. The pattern basically says, at the start of the subject string does it a) contain only alphanumeric characters between 8 and 20 in length, b) contain something (or nothing) then a digit, and c) contain something (or nothing) followed by a letter.

 

Reading:

http://www.regular-expressions.info/anchors.html

http://www.regular-expressions.info/lookaround.html

Also, as a consultant, part of your job is to tell a client when they're purposely making their system less secure and less functional.  My passwords always contain non alphanum characters.  Do you know why?  Because that's what you're supposed to do.  Making your passwords less secure is a bad idea, and you should at least mention that.

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.