php - Password Regular expression with four criteria -


i trying write regular expression in php ensure password matches criteria is:

  • it should atleast 8 characters long
  • it should include @ least 1 special character
  • it should include @ least 1 capital letter.

i have written following expression:

$pattern=([a-za-z\w+0-9]{8,}) 

however, doesn't seem work per listed criteria. pair of eyes aid me please?

your regex - ([a-za-z\w+0-9]{8,}) - searches substring in larger text @ least 8 characters long, allowing english letters, non-word characters (other [a-za-z0-9_]), , digits, does not enforce 2 of requirements. can set look-aheads.

here fixed regex:

^(?=.*\w.*)(?=.*[a-z].*).{8,}$ 

actually, can replace [a-z] \p{lu} if want match/allow non-english letters. can consider using \p{s} instead of \w, or further precise criterion of special character adding symbols or character classes, e.g. [\p{p}\p{s}] (this include unicode punctuation).

an enhanced regex version:

^(?=.*[\p{s}\p{p}].*)(?=.*\p{lu}.*).{8,}$ 

a human-readable explanation:

  • ^ - beginning of string
  • (?=.*\w.*) - requirement have @ least 1 non-word character
    or (?=.*[\p{s}\p{p}].*) - @ least 1 unicode special or punctuation symbol
  • (?=.*[a-z].*) - requirement have @ least 1 uppercase english letter
    or (?=.*\p{lu}.*) - @ least 1 unicode letter
  • .{8,} - requirement have at least 8 symbols
  • $ - end of string

see demo 1 , demo 2 (enhanced regex)

sample code:

if (preg_match('/^(?=.*\w.*)(?=.*[a-z].*).{8,}$/u', $header)) {  // pass }  else {     # fail } 

Comments

Popular posts from this blog

shopping cart - Page redirect not working PHP -

php - How to modify a menu to show sub-menus -

python - Installing PyDev in eclipse is failed -