2

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 follow piece of code does not seem to work properly. It should return true if there is any illegal character in the string $username. However, it still allows any character in the string. Any idea what is wrong with the regular expression?

if ( !preg_match("/^[-a-z0-9_]/i", $username) )
{
    return true;
}

Thanks in advance.

5 Answers 5

16

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.

Sign up to request clarification or add additional context in comments.

1 Comment

This solution is better than the ones matching entire strings, since preg_match can return true as soon as it encounters a non-allowed character. It won't matter much on something as short as a username, though.
2

If $username only has alphanumeric and underscore it will return TRUE

if (preg_match("/^[a-z0-9_]+$/i", $username) )
{
    return true;
}

Comments

1

Your expression matches only 1 character. Try /^[-a-z0-9_]+$/i the '+' matches more then 1 character and the '$' is the end of line anchor

Comments

1

You need to anchor it at the end too, instead of just checking the first character. Try "/^[-a-z0-9_]*$/i" instead.

Comments

0

You have no repeater for one. You need a repeater such as +. As far as I can see without executing it, you check start of line and one character matching a-zA-Z0-9 and _ but nothing following that first character.

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.