如果我有一个网页,并且希望确保用户输入的变量只有字母(上下),数字和破折号且长度必须恰好为20个字符,那么如何执行呢?
This is pretty easy to do using regular expressions:
echo preg_match('/^[0-9a-zA-Z\-]{20}$/', 'abcd');
0
echo preg_match('/^[0-9a-zA-Z\-]{20}$/', 'abcdefghijkmlnopqrst');
1
You can use regular expressions. See preg_match
.
Your regular expression could look something like:
/^[A-Za-z0-9\-]{20}$/
or
/^[\w-]{20}$/
if you don't trust in regexp because of performance you may use the following, which will take longer:
function checkalphanum($str){
$allowed = "0123456789abcdefghijklmnopqrstuvwxyz_-ABCDEFGHIJKLMNOPQRSTUVWXYZ";
if(strlen($str) == 20){ return false;}
for($i=0; $i < count($str); $i++){
if(strpos($allowed, substr($str, $i, 1)) == -1){
return false;
}
}
return true;
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.