PHP username validation

if(preg_match('/^\w{5,}$/', $username)) { // \w equals "[0-9A-Za-z_]"
    // valid username, alphanumeric & longer than or equals 5 chars
}

OR

if(preg_match('/^[a-zA-Z0-9]{5,}$/', $username)) { // for english chars + numbers only
    // valid username, alphanumeric & longer than or equals 5 chars
}

If you don't care about the length, you can use:

if (ctype_alnum($username)) {
   // Username is valid
}

http://www.php.net/manual/en/function.ctype-alnum.php


The Best way I recommend is this :-

$str = "";
function validate_username($str) 
{
    $allowed = array(".", "-", "_"); // you can add here more value, you want to allow.
    if(ctype_alnum(str_replace($allowed, '', $str ))) {
        return $str;
    } else {
        $str = "Invalid Username";
        return $str;
    }
}

Tags:

Php