Reputation: 9291
If I had a webpage and I neeed to ensure user input for a variable is only letters (upper and lower), numbers and dashes and the length had to be exactly 20 chars in length, how would one perform that?
Upvotes: 3
Views: 5700
Reputation: 257
You can use regular expressions. See preg_match
.
Your regular expression could look something like:
/^[A-Za-z0-9\-]{20}$/
or
/^[\w-]{20}$/
Upvotes: 3
Reputation: 83
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;
}
Upvotes: 0
Reputation: 3358
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
Upvotes: 5