为密码验证创建 preg_match 允许 (!@#$%)

2022-01-22 00:00:00 regex passwords php preg-match

我想创建一个 preg_match 函数来验证我的密码,但我不确定如何编写它以允许使用以下特殊字符:!@#$%.

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:

  • 可能包含字母和数字
  • 必须至少包含 1 个数字和 1 个字母
  • 可能包含以下任何字符:!@#$%
  • 必须为 8-12 个字符

感谢您提供的任何帮助.

Thank you for any help you can offer.

推荐答案

我觉得应该是这样的:

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

开始之间 -> ^
并结束 -> $
字符串中必须至少有一个数字 -> (?=.*d)
和至少一个字母 -> (?=.*[A-Za-z])
它必须是数字、字母或以下之一:!@#$% -> [0-9A-Za-z!@#$%]
并且必须有 8-12 个字符 -> {8,12}

正如 user557846 对您的问题的评论,我还建议您允许更多字符,我通常(如果我使用最大值)至少需要 50 个 :)

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

相关文章