8

I am working on writing a PHP login system. I have everything that I need working, but I would like to verify that a username entered during the registration only contains alphanumeric characters. So how could I take a variable, say $username, and ensure that it contained only alphanumeric characters?

6 Answers 6

32
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
}
4
  • Hey, thanks for the speedy answer! I have to wait 10minutes before it'll let me accept your answer, so I'll do it later. Commented Dec 8, 2010 at 3:28
  • 1
    preg_match is better suited here, also there is no need for character class.
    – codaddict
    Commented Dec 8, 2010 at 3:32
  • 1
    The square brackets are redundant if you're only targeting one character or special character set (\w)
    – Phil
    Commented Dec 8, 2010 at 3:34
  • 1
    Also the definition of \w depends on the locale. If OP want to allow only English letters, it's safer to enumerate them.
    – codaddict
    Commented Dec 8, 2010 at 3:35
8

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

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

1

try this

function filterName ($name, $filter = "[^a-zA-Z0-9\-\_\.]"){
    return preg_match("~" . $filter . "~iU", $name) ? false : true;
}

if ( !filterName ($name) ){
 print "Not a valid name";
}
1

A little bit late but I am using the following function to test usernames or other types of alphanum-like strings. It tests alphanum chars only by default but you can add more characters such as . (dot), - (dash) or _ (underscore) to the whitelist.

It will also prevent consecutive chars for the chars specified as $more_chars.

function valid_alphanum_string($str, $more_chars = '') {
  # check type
  if (!is_string($str)) return false;

  # handle allowed chars
  if (mb_strlen($more_chars) > 0) {
    # don't allow ^, ] and \ in allowed chars
    $more_chars = str_replace(array('^', ']', '\\'), '', $more_chars);

    # escape dash
    $escaped_chars = strpos($more_chars, '-') !== false
      ? str_replace('-', '\-', $more_chars)
      : $more_chars;

    # allowed chars must be non-consecutive
    for ($i=0; $i < mb_strlen($more_chars); $i++) {
      $consecutive_test = preg_match('/[' . $more_chars[$i] . '][' . $escaped_chars . ']/', $str);
      if ($consecutive_test === 1) return false;
    }

    # allowed chars shouldn't be at the start and the end of the string
    if (strpos($more_chars, $str[0]) !== false) return false;
    if (strpos($more_chars, $str[mb_strlen($str) - 1])) return false;
  }
  else $escaped_chars = $more_chars;

  $result = preg_match('/^[a-zA-Z0-9' . $escaped_chars . ']{4,}$/', $str);

  return $result === 1 ? true : false;
}
0

If you are allowing the basic alpha-numeric username, You can check alphanumeric value with a predefined template like this:

preg_match([[:alnum:]],$username)&&!preg_match([[:space:]],$username)

The second part returns false if the string contains any spaces.

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.