I want to check a for any illegal character using the following regular expression in PHP. Essentially, I want to allow only alphanumeric and underscore (_). Unfortunately the
Your code checks to see if the first character is not valid. To check to see if any invalid characters exist, negate your character class rather than the function return and remove the anchor:
if ( preg_match("/[^-a-z0-9_]/i", $username) )
{
return true;
}
You could also, of course, shorten it to /[^-\w]/
("word" characters are letters, numbers, and the underscore), or even just /\W/
if you don't want to allow dashes.