I would use this one:
/^[a-z_\-\d]+$/i
As to why I'm not using \w
, the following quote, taken from PHP PCRE Pattern Reference, should explain why you shouldn't be using \w
in this situation:
A "word" character is any letter or digit or the underscore character, that is, any character which can be part of a Perl "word". The definition of letters and digits is controlled by PCRE's character tables, and may vary if locale-specific matching is taking place. For example, in the "fr" (French) locale, some character codes greater than 128 are used for accented letters, and these are matched by \w
.
That behavior is not desirable in this case, so unless you want to worry about locale, use straight character classes instead of the \w
shorthand.
If you want to specify a minimum length (for example 3):
/^[a-z_\-\d]{3,}$/i
If you want to specify both a minimum and maximum length (for example 2 and 5):
/^[a-z_\-\d]{2,5}$/i