3

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. Commented Feb 25, 2012 at 23:56
  • 1
    Looks like assignment specification. Commented Feb 26, 2012 at 0:02

3 Answers 3

5

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
Sign up to request clarification or add additional context in comments.

Comments

3

You can use regular expressions. See preg_match.

Your regular expression could look something like:

/^[A-Za-z0-9\-]{20}$/

or

/^[\w-]{20}$/

Comments

0

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;
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.