跟进PHP正则表达式以将字母数字字符串与某些(但不是全部)标点符号匹配,我必须接受至少2种类型的字符,这些字符必须是数字,字母或标点之一,而字符串必须介于长度为6和18个字符。这是最好的方法吗?我使用RegExLib的模式构造了此正则表达式。
preg_match('@' .
// one number and one letter
'^(?=.*\d)(?=.*[a-zA-Z])[!-%\'-?A-~]{6,18}$' .
// one number and one punctuation
'|^(?=.*\d)(?=.*[!-%\'-/:-?\[-`{-~])[!-%\'-?A-~]{6,18}$' .
// or one punctation and one
'|^(?=.*[!-%\'-/:-?\[-`{-~])(?=.*[a-zA-Z])[!-%\'-?A-~]{6,18}$' .
'@i', $pass, $matches);
Run Code Online (Sandbox Code Playgroud)
您的解决方案太复杂了。只需检查char类型和长度的存在。
<?php
$is_special = preg_match('/[+#!\?]/', $pass); //sample only
$is_numeric = preg_match('/[0-9]/', $pass);
$is_char = preg_match('/[a-zA-Z]/', $pass);
if ($is_special + $is_numeric + $is_char < 2) {
//fail
}
//+lenght check
Run Code Online (Sandbox Code Playgroud)