4

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

  • AZ
  • 阿兹
  • 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';
4

3 回答 3

12

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

^(?=.{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
于 2012-07-03T21:01:02.340 回答
1
((?=(.*\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
于 2012-07-03T20:58:57.990 回答
0

对于匹配长度的字符串,包括特殊字符:

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

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

于 2017-09-22T07:45:32.693 回答