Reputation: 405
I'm trying to validate usernames in PHP using preg_match()
but I can't seem to get it working the way I want it. I require preg_match()
to:
preg_match('/^[a-zA-Z0-9]+[.-_]*[a-zA-Z0-9]{5,20}$/', $username)
Upvotes: 3
Views: 4504
Reputation: 490423
If the regex is confusing you, you could always match the characters with a regex and then explicitly check for the length of the string with strlen()
.
$valid = preg_match('/^[a-zA-Z\d]+[\w.-]*[a-zA-Z\d]$/', $username)
AND strlen($username) >= 5 AND strlen($username) <= 20;
Upvotes: 2
Reputation: 33457
Break down the requirements into smaller pieces and you'll see that it becomes a lot easier:
~^[a-z0-9]{1}[a-z0-9._-]{3,18}[a-z0-9]{1}$~i
Upvotes: 6
Reputation: 154603
if (preg_match('~^[0-9a-z][-_.0-9a-z]{3,18}[0-9a-z]$~i', $username) > 0)
{
// valid
}
Upvotes: 2