You are asking for a lot in one regex, this may be possible but it is not the best way, you want to let the user know why their username is erroring out.
function checkUsername($username) {
$username = trim($username);
if (empty($username)) {
return "username was left blank.";
}elseif (strlen($username) < 4) {
return "username was too short";
}elseif (strlen($username) > 26) {
return "username was too long";
}elseif (!preg_match('~^[a-z]{2}~i', $username)) {
return "username must start with two letters";
}elseif (preg_match('~[^a-z0-9_.]+~i', $username)) {
return "username contains invalid characters.";
}elseif (substr_count($username, ".") > 1) {
return "username may only contain one or less periods.";
}elseif (substr_count($username, "_") > 1) {
return "username may only contain one or less underscores.";
}
return true;
}
Then to check you would do:
$validUsername = checkUsername($username);
if ($validusername !== true) {
echo "An error occured: " . $validUsername;
}
This way the user knows there was an error and can fix it easier instead of being blind to what the error is. Also you should stop using ereg it has been depreciated use preg_match instead.
NOTE the use of the !== to check, this also checks type since it can return a string (which would return true with a loose comparison). Just an FYI.