我想使用正则表达式来限制允许的字符。那就是:
a - z /* a to z */
A - Z /* A to Z */
0 - 9 /* 0 to 9 */
_ - /* underscore & dash */
~ ! @ # $% ^ & * () /* allowed special characters */
这是我的正则表达式函数:
function validChr($str) {
return preg_match('/^[A-Za-z0-9_~\-!@#\$%\^&*\(\)]+$/',$str);
}
我实际上已经按照我的意愿尝试了它,但我仍然不确定。我的正则表达式是正确的吗?还是有其他形式的正则表达式?请帮助我,因为我仍然是这个正则表达式的新手。谢谢。
答案 0 :(得分:9)
答案 1 :(得分:0)
您可以使用我之前创建的此功能来输入密码。您可以通过修改if条件来将其用于任何字符串。在每个特殊字符前加上 \ 。还可以检查字符串长度为8-20个字符
function isPasswordValid($password){
$whiteListed = "\$\@\#\^\|\!\~\=\+\-\_\.";
$status = false;
$message = "Password is invalid";
$containsLetter = preg_match('/[a-zA-Z]/', $password);
$containsDigit = preg_match('/\d/', $password);
$containsSpecial = preg_match('/['.$whiteListed.']/', $password);
$containsAnyOther = preg_match('/[^A-Za-z-\d'.$whiteListed.']/', $password);
if (strlen($password) < 8 ) $message = "Password should be at least 8 characters long";
else if (strlen($password) > 20 ) $message = "Password should be at maximum 20 characters long";
else if(!$containsLetter) $message = "Password should contain at least one letter.";
else if(!$containsDigit) $message = "Password should contain at least one number.";
else if(!$containsSpecial) $message = "Password should contain at least one of these ".stripslashes( $whiteListed )." ";
else if($containsAnyOther) $message = "Password should contain only the mentioned characters";
else {
$status = true;
$message = "Password is valid";
}
return array(
"status" => $status,
"message" => $message
);
}
输出
$password = "asdasdasd"
print_r(isPasswordValid($password));
// [
// "status"=>false,
// "message" => "Password should contain at least one number."
//]
$password = "asdasd1$asd"
print_r(isPasswordValid($password));
// [
// "status"=>true,
// "message" => "Password is valid."
//]