【问题标题】:PHP regex for password validation用于密码验证的 PHP 正则表达式
【发布时间】:2012-07-03 20:55:34
【问题描述】:

我没有从脚本中获得预期的效果。我希望密码包含 A-Z、a-z、0-9 和特殊字符。

  • A-Z
  • a-z
  • 0-9 >= 2
  • 特殊字符 >= 2
  • 字符串长度 >= 8

所以我想强制用户使用至少 2 个数字和至少 2 个特殊字符。好的,我的脚本有效,但迫使我背靠背使用数字或字符。我不想要那个。例如密码 testABC55$$ 是有效的 - 但我不希望这样。

相反,我希望 test$ABC5#8 有效。所以基本上数字/特殊字符可以相同或不同->但必须在字符串中拆分。

PHP 代码:

$uppercase = preg_match('#[A-Z]#', $password);
$lowercase = preg_match('#[a-z]#', $password);
$number    = preg_match('#[0-9]#', $password);
$special   = preg_match('#[\W]{2,}#', $password); 
$length    = strlen($password) >= 8;

if(!$uppercase || !$lowercase || !$number || !$special || !$length) {
  $errorpw = 'Bad Password';

【问题讨论】:

  • 好的,那段代码有什么问题?
  • 我很确定,您可以将它组合成一个正则表达式。
  • 代码可以正常工作,但不能达到预期的效果。注意我上面的 pw 示例
  • 我只是在强制用户设置更安全的密码。我如何“阻止”你,达贡?我没有看到问题。在我看来,您的“首选密码”可能很弱。
  • 简单的答案是,不要使用正则表达式。正则表达式不是为此而设计的,您可以根据自己的意愿扭曲其手臂所需要付出的努力可以用来轻松创建更有效的解决方案。

标签: php regex


【解决方案1】:

使用“可读”格式(可以优化为更短),因为你是正则表达式新手>>

^(?=.{8})(?=.*[A-Z])(?=.*[a-z])(?=.*\d.*\d.*\d)(?=.*[^a-zA-Z\d].*[^a-zA-Z\d].*[^a-zA-Z\d])[-+%#a-zA-Z\d]+$

在上面的正则表达式中将您的特殊字符集添加到最后一个[...](我现在只是放在那里-+%#)。


解释:

^                              - beginning of line/string
(?=.{8})                       - positive lookahead to ensure we have at least 8 chars
(?=.*[A-Z])                    - ...to ensure we have at least one uppercase char
(?=.*[a-z])                    - ...to ensure we have at least one lowercase char
(?=.*\d.*\d.*\d                - ...to ensure we have at least three digits
(?=.*[^a-zA-Z\d].*[^a-zA-Z\d].*[^a-zA-Z\d]) 
                               - ...to ensure we have at least three special chars
                                    (characters other than letters and numbers)
[-+%#a-zA-Z\d]+                - combination of allowed characters
$                              - end of line/string

【讨论】:

  • Omega,感谢您的回复,但是我发现您的 RegEx 形式令人困惑,因为我是新手。你能详细说明一下这段代码吗?
  • 不错的答案... (?= 是以前看还是以后看?顺便说一句,你应该解释一下。
  • @FabioAnselmo - 我已经用这些信息更新了我的答案
  • @rekire - (?= ... ) 是一个积极的前瞻(见更新的答案)
  • 如何 (?=.*[^a-zA-Z\d].*[^a-zA-Z\d]) 确保特殊字符? RegEx 参考将 \W 显示为特殊字符。不过感谢您的解释。同样对于允许的字符 - 说我想要 @#$ 会像这样:[/@/#/$a-zA-Z\d]+
【解决方案2】:
((?=(.*\d){3,})(?=.*[a-z])(?=.*[A-Z])(?=(.*[!@#$%^&]){3,}).{8,})

test$ABC5#8 无效,因为您询问的数字和规格符号超过 2 个

A-Z
a-z
0-9 > 2
special chars > 2
string length >= 8

【讨论】:

  • 您好,很抱歉给您带来了困惑。注意代码。它是无效的,因为字符不相邻。例如,它验证我是否使用:test$$ABC44 我将更正该示例。对不起
  • 将数字和规格符号中的 {3,} 切换为 {2,} 即可通过
【解决方案3】:

用于匹配包含特殊字符的字符串长度:

$result = preg_match('/^(?=.[a-z])(?=.[A-Z])(?=.\d)(?=.[^A-Za-z\d])[ \s\S]{6,16}$/', $string);

答案解释:https://stackoverflow.com/a/46359397/5466401

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-07-10
    • 2011-07-10
    • 1970-01-01
    • 2014-10-14
    • 2023-03-12
    • 2011-04-17
    • 2018-03-16
    相关资源
    最近更新 更多