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.

Link to comment
Share on other sites

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

Link to comment
Share on other sites

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.

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • 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.