我需要验证符合以下条件的密码:
为此我在互联网上找到了一个有点匹配的RegEx,并根据我的要求进行了修改。
<?php
$pwd = "Abcdef.1";
if (preg_match("^(?=.*\d)(?=.*[a-z])(?=.*[A-Z])(?=.*[_.@#$&]).{8,15}$", $pwd)){
echo 'Match Found';
}
else{
echo 'No Match Found';
}
?>
执行脚本时,PHP会发出警告: No Match FoundPHP警告:preg_match():在第3行的[my_file_path] .php中找不到结束分隔符'^'
请帮忙吗?
答案 0 :(得分:1)
您需要将模式包含在“//”中,如下所示:
preg_match("/^(?=.*\d)(?=.*[a-z])(?=.*[A-Z])(?=.*[_.@#$&]).{8,15}$/", $pwd)
编辑:
好吧所以我实际上将大而混乱的正则表达式线分成多个正则表达式模式,每个约束对应一个,它会更容易阅读和理解,而且你可以给用户更多的描述性暗示什么当前输入密码的问题(它是否太短,是否缺少符号,是否缺少大写字母..你明白了......)
以下是代码:
<?php
function validatePassword($pass)
{
$uppercasePattern = "/[A-Z]/";
$lowercasePattern = "/[a-z]/";
$symbolPattern = "/[\.\$@_#&]/";
$digitPattern = "/[0-9]/";
$unwantedSymbolsPattern = "/[^\w\.\$@_#&]/";
$len = strlen($pass);
if($len >=8 && $len <= 15){ // check if length is 8 - 15
$hasUppercase = false;
preg_match($uppercasePattern, $pass, $hasUppercase); // check if has uppercase letter
if(!empty($hasUppercase)){
$hasLowercase = false;
preg_match($lowercasePattern, $pass, $hasLowercase); // check if has lowercase letter
if(!empty($hasLowercase)){
$hasSymbol = false;
preg_match($symbolPattern, $pass, $hasSymbol); // check if has symbol
if(!empty($hasSymbol)){
$hasDigit = false;
preg_match($digitPattern, $pass, $hasDigit); // check if has digit
if(!empty($hasDigit)){ // check if contains needed symbol
$hasUnwantedSymbols = false;
preg_match($unwantedSymbolsPattern, $pass, $hasUnwantedSymbols);
if(empty($hasUnwantedSymbols)){ // if doesnt contain unwanted symbols return true
return true;
}else{
echo "Password contains some of the unwanted symbols!";
}
}else{
echo "Missing digit!";
}
}else{
echo "Missing on of the following symbols: . _ @ $ # &";
}
}else{
echo "Missing uppercase letter!";
}
}else{
echo "Missing uppercase letter!";
}
}
else{
echo "Password length not OK!";
}
}
$pass = "Abcdef@1as#(";
// call the function to test it out
if(validatePassword($pass)){
echo "OK";
}
?>