-7

I am completely new to PHP. I need help writing a regex which validates a password. The password must be at least 8 chars in length, begin with a letter, end with a digit, and is case insensitive. The characters in between the first and last can be a digit, underscore, or symbol.

Any help would be greatly appreciated.

user2573918
  • 13
  • 1
  • 3
  • 3
    Have a look at [this](http://stackoverflow.com/q/11873990/2493918) question. – Markus Hofmann Jul 11 '13 at 18:45
  • which symbols are acceptable for the middle characters? – Legion Jul 11 '13 at 18:50
  • 4
    Why are you forcing a letter as the first character? And restricting the character set that I can use to letters, digits, underscores and symbols? Can't I use UTF-8 characters? – Mark Baker Jul 11 '13 at 18:51
  • 2
    Why are you limiting the length? Why should that matter? You're hashing the password--with some kind of salt--on the back end, right? **Right?** –  Jul 11 '13 at 18:54
  • Possible duplicate of [Enforcing Password Requirements](http://stackoverflow.com/questions/6182846/enforcing-password-requirements) – Jason McCreary Jul 11 '13 at 18:55
  • the middle characters can be a digit, underscore, or letter – user2573918 Jul 11 '13 at 18:55
  • 3
    case insensitive is a bad idea for a password security - it drastically reduces the amount of effort needed to crack it. (and in any case, it's probably not relevant to the regex anyway, since you'd need the regex to accept upper or lower case characters either way) – Spudley Jul 11 '13 at 18:55

2 Answers2

2

/^[A-Za-z][0-9[:punct:]]{6,}[0-9]$/ should work

this says:

  • the first character must be a letter
  • middle characters must be digit or symbol (underscore included)
  • there must be at least 6 middle characters
  • the last character must be a digit
Legion
  • 796
  • 7
  • 12
0

Have a look at the preg_match() PHP function in the manual.

Quick Example:

<?php
// Check if the string is at least 8 chars long
if (strlen($password) < 8)
{
   // Password is too short
}


// Make the password "case insensitive"
$password = strtolower($password);


// Create the validation regex
$regex = '/^[a-z][\w!@#$%]+\d$/i';

// Validate the password
if (preg_match($regex, $password))
{
   // Password is valid
}
else
{
   // ... not valid
}

­

Regex Explanation:  
   ^           => begin of string
   [a-z]       => first character must be a letter
   [\w!@#$%]+  => chars in between can be digit, underscore, or symbol
   \d          => must end with a digit
   $           => end of string
   /i          => case insesitive
Markus Hofmann
  • 3,427
  • 4
  • 21
  • 31