Search code examples
phpregexwhitelist

php regex syntax to whitelist alphanumeric


I am trying to use preg_match to whitelist usernames with alphanumeric characters and screen out those with special characters but code is not acting as I'd like

Here is is:

PHP

$username = "karl#";
if (!preg_match("#^[a-zA-Z0-9]+$#", $username))
{
$msg = "You may not use special characters in your username";
}
else {
$msg = "ok";
}

returns "ok". In other words, it is letting karl# get through. I would like it to return error message.

Am I misusing preg-match or what am I doing wrong? Thank you for any suggestions.

Edit: The code above does work. Error was because in original version I was not hard coding the username but rather getting it as post and there was a problem with post. I accepted the answer below using ^\w+$ as it allows for underscore and is more concise. Thanks also for all the fine points on regex contained in comments.


Solution

  • You can use this regex:

    ^\w+$
    

    Working demo

    As Barmar pointed in the comment this will allow underscores too, but if you don't want them then your regex is fine:

    ^[a-zA-Z0-9]+$
    

    You need to help the regex with the flags:

    $re = "/^[a-zA-Z0-9]+$/m"; 
    $username = "karl#";   ^----Notice the multiline flag
    

    You also could use:

    $re = "/^[a-z0-9]+$/mi"; 
                         ^---- Case Insensitive flag