我在PHP中创建了一个preg_match($pattern, $password)
函数的$模式,它应该是一个regexp,定义了一个这样的字符串:
- 至少
$str_lenght
长AND - 包含至少
$num_capitals
个大写字母和 - 至少有
$num_numerals
号和 - 至少有
$num_symbols
从这个范围:!@#$%^&*()-+?
我该怎么做?
你可以用这种方式构建你的正则表达式:
$re = '/(?=(.*?[A-Z]){' . $num_capitals . '})(?=(.*?[0-9]){' . $num_numerals .
'})(?=(.*?[!@#$%^&*()+?-]){' . $num_symbols . '}).{' . $str_lenght . ',}/';
@anubhava极大地破坏了我的答案,但我将把它留给另一个方法
.
匹配所有字符,{5,}
重复它5次以上。然而,由于我们没有制作一个长表达式,我仍然会使用更快的strlen()
。演示:
.{5,}
对于其余部分,我将匹配一个字符类并使用preg_match_all()
,它将返回匹配的总数(可能是0)。
这是你想要的3个字符类:
[A-Z]
[0-9] OR 'd ('d will match other numeric characters, like Arabic, etc.)
[!@#$%^&*()+?-]
示例实现:
$count = preg_match_all('/[A-Z]/', 'FOObar', $matches);
// $count = 3;
请注意在最后的字符类([!@#$%^&*()+?-]
)中,^
不能出现在前面,-
不能出现在中间,否则你需要用'
转义,因为它们有特殊的含义。
试试这个
$strRegex = '/((?=.*'d).{'.$num_numerals.'})((?=.*[a-z]).{'.$num_lower.'})((?=.*[A-Z]).{'$num_upper'})((?=.*[@#$%]).{'.$num_symbols.'})/';
或
$strRegex = '/((?=.*'d).{'.$num_numerals.'})((?=.*[a-z]).{1,'.$num_lower.'})((?=.*[A-Z]).{'$num_upper'})((?=.*[@#$%]).{'.$num_symbols.'})/';
基于$num_lower,您可以限制密码中允许的字符数。pass将接受从1到$num_lower