Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
681 views
in Technique[技术] by (71.8m points)

php - Create preg_match for password validation allowing (!@#$%)

I would like to create a preg_match function to validate my passowrds, but I'm not sure how to write it to allow the following special characters to be used: !@#$%.

if(!preg_match(?????)$/', $password))

Here are my password rules that I want to work into the regex:

  • May contain letter and numbers
  • Must contain at least 1 number and 1 letter
  • May contain any of these characters: !@#$%
  • Must be 8-12 characters

Thank you for any help you can offer.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

I think this should look like that:

if(!preg_match('/^(?=.*d)(?=.*[A-Za-z])[0-9A-Za-z!@#$%]{8,12}$/', $password)) {
    echo 'the password does not meet the requirements!';
}

Between start -> ^
And end -> $
of the string there has to be at least one number -> (?=.*d)
and at least one letter -> (?=.*[A-Za-z])
and it has to be a number, a letter or one of the following: !@#$% -> [0-9A-Za-z!@#$%]
and there have to be 8-12 characters -> {8,12}

As user557846 commented to your question, I would also suggest you to allow more characters, I usually (if i use a maximum) take at least 50 :)

btw, you might want to take a look at this regex tutorial


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...