PHP:仅正则表达式字母数字和一些特殊字符
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/13621223/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
PHP: Regex alphanumeric and some special characters only
提问by Fredy
I want to use a regex to limit the characters allowed. That is:
我想使用正则表达式来限制允许的字符。那是:
a - z /* a to z */
A - Z /* A to Z */
0 - 9 /* 0 to 9 */
_ - /* underscore & dash */
~ ! @ # $% ^ & * () /* allowed special characters */
and this is my regex function:
这是我的正则表达式函数:
function validChr($str) {
return preg_match('/^[A-Za-z0-9_~\-!@#$%\^&*\(\)]+$/',$str);
}
I've actually tried it and the result as I want, but I still was not sure. Is my regex is correct? Or are there other forms regex? Please help as I am still new about this regex. Thank you.
我实际上已经尝试过了,结果如我所愿,但我仍然不确定。我的正则表达式正确吗?还是有其他形式的正则表达式?请帮忙,因为我对这个正则表达式还是个新手。谢谢你。
回答by Matija
It works as it should.
它可以正常工作。
You should only add \ before * to escape it.
您应该只在 * 之前添加 \ 来转义它。
Check it out here: Regular expression test
在这里查看:正则表达式测试
回答by Raj Sharma
You can use this function I made sometime ago for passwords. You can use it for any string by modifying the if coniditions. Put each special characters with a \before. It also has a check for string to be 8-20 characters long
你可以使用我前段时间做的这个函数来获取密码。您可以通过修改 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
);
}
Output
输出
$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."
//]

