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.