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?
2
-
You can figure out the regex part in this question. The string length part should be pretty simple.animuson– animuson ♦2012-02-25 23:56:27 +00:00Commented Feb 25, 2012 at 23:56
-
1Looks like assignment specification.Shiplu Mokaddim– Shiplu Mokaddim2012-02-26 00:02:23 +00:00Commented Feb 26, 2012 at 0:02
Add a comment
|
3 Answers
You can use regular expressions. See preg_match.
Your regular expression could look something like:
/^[A-Za-z0-9\-]{20}$/
or
/^[\w-]{20}$/
Comments
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;
}