[英]PHP: Regex alphanumeric and some special characters only
我想使用正則表達式來限制允許的字符。 那是:
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);
}
我實際上已經按照我的意願嘗試了它,但我仍然不確定。 我的正則表達式是正確的嗎? 還是有其他形式的正則表達式? 請幫助我,因為我仍然是這個正則表達式的新手。 謝謝。
你可以使用我之前制作的這個函數來獲取密碼。 您可以通過修改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."
//]
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.