0

I have been trying to make a reg_match for the username to only accept a-z, A-Z ,0-9,-, and _ unfortunately all my attempts have failed.

function usernameValidation($username){
    $re =  "/[\w_-]/g";
    return preg_match($re, $username);
}
$username = "skjdasASD345-_adadasda";
if(usernameValidation($username)){
    echo "success!!";
}else{
    echo "Fail!"; //it always return fail.
}

my code always returns fail, can anyone tell me what i am doing wrong?

  • @mario The real problem here is a quirk in OP's particular platform. That question is too general. – p.s.w.g Nov 09 '13 at 04:50
  • 1
    @p.s.w.g We have hundreds of [duplicates on this](https://www.google.com/search?q=site:stackoverflow.com+php%20regex%20match%20whole%20string#q=site:stackoverflow.com+php+regex+match+whole+string). I fail to see the novelty or research here. – mario Nov 09 '13 at 05:03
  • @mario Then it may legitimately be closed as a duplicate of one of those questions. I'm not saying it shouldn't be closed; I just feel like a question dealing with a platform-specific issue shouldn't be marked as a duplicate of a very general question which doesn't address that issue. – p.s.w.g Nov 09 '13 at 05:10
  • @p.s.w.g I see OPs main problem here in not enabling `error_reporting` after seeing the code misbehave repeatedly. That would have revealed a warning ["Unknown modifier 'g' in..." when using preg\_match in PHP?](http://stackoverflow.com/q/3578671) about JS and PCRE syntax differences. But true, there are more exact references [somewhere..] – mario Nov 09 '13 at 05:32
  • @mario You're right, that is an underlying issue as well, and I should have mentioned that in my answer for completeness. – p.s.w.g Nov 09 '13 at 05:49

1 Answers1

0

The problem is that the g modifier doesn't work with preg_match; that's what preg_match_all is for. If you have enabled error reporting (see How to get useful error messages in PHP?) you should've seen a warning about this along the lines of:

Warning: preg_match() [function.preg-match]: Unknown modifier 'g' on line #

However, if you fix that, there's still the problem that your pattern will match any string which contains a word character or hyphen anywhere. It won't care if there are other invalid characters.

Try using this pattern

$re = '/^[\w-]+$/';

This will match the start of the string, followed by one or more word characters or hyphens followed by the end of the string.

Also note that the behavior of \w varies by locale, meaning that what usernames are allowed depends on the server's configuration. If you really only want to match only a-z or 0-9, regardless of locale, you should specify those characters explicitly:

$re = '/^[a-z0-9_-]+$/i';

The i flag here makes the pattern case-insensitive, meaning it will allow uppercase characters as well.

Community
  • 1
  • 1
p.s.w.g
  • 136,020
  • 27
  • 262
  • 299