用于密码验证的 PHP 正则表达式在不同环境中失败

问题描述 投票:0回答:2

我们使用以下函数根据客户要求验证密码。这在我们的开发环境以及客户的登台环境中都有效,但在推送到生产环境时密码会随机失败。登台和生产应该是相同的,因此很难弄清楚为什么它不起作用,因为我们无法访问生产环境。

密码需要验证以下内容:

  1. 至少 1 个大写字母和 1 个小写字母字符
  2. 至少 1 位数字 (0-9)
  3. 长度至少10个字符
  4. 包含以下字符 1 -
    !@#$%^&*()
    Shift + 标准美国键盘上的任何数字)
  5. 只要上述内容有效,就没有特定的顺序

该代码可以在我们的开发环境中运行,因此它也可能适合您。我们需要的是看看为什么它可能会失败并且

<?php
function isStrongPassword($pass, $char = 10) {
     $bits = ['A-Z', 'a-z', '0-9',preg_quote('#$%^&*()','/')];
         if (is_numeric($char) && strlen($pass) >= $char) {
              foreach ($bits AS $bit) {
                  if (preg_match('@[' . $bit . ']@', $pass) == false) {
                      return false;
                  }
              }
              return true;
          }
          return false;
       }
?>
php regex passwords
2个回答
0
投票

将我的评论转化为答案。

似乎答案中的所有代码都可以使用前瞻转换为单个正则表达式,如下所示:

/^(?=.*[A-Z])(?=.*[a-z])(?=.*[0-9])(?=.*[!@#$%^&*()]).{10,}$/

4 个前瞻

(?=...)
中的每一个都确保存在大写字母、小写字母、数字和特殊字符。
.{10,}
确保输入的最小长度为 10。


0
投票

这与其他答案之一类似,但匹配并需要除空格之外的任何字母数字和非单词字符:

/^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*\W)[0-9A-Za-z\W][^\s]{10,}$/

作为函数:

<?php
function isStrongPassword($pass) {
    if(!preg_match('/^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*\W)[0-9A-Za-z\W][^\s]{10,}$/',$pass){
        //do something here
        return false;
    } else {
        //do something here
        return true;
    }
}

答案解释

//look ahead match/require at least 1 lowercase
(?=.*[a-z])

//look ahead match/require at least 1 uppercase
(?=.*[A-Z])

//look ahead match/require at least 1 number
(?=.*\d)

//look ahead match/require at least 1 non-word character
(?=.*\W)

//specify all chars except space and set a min. of 10 and max unlimited
[0-9A-Za-z\W][^\s]{10,}
© www.soinside.com 2019 - 2024. All rights reserved.