Warning: preg_match() [function.preg-match]: Compilation failed: nothing to repeat at offset

i'm trying to change the preg_match check from url checking to username checking which is min/max 2-16chrs, dash, space & hypen acceptable. i'm getting this error


Warning: preg_match() [function.preg-match]: Compilation failed: nothing to repeat at offset 14


if(empty($string) || preg_match("#^([\w- ]{2,16}*(?:.[\w- ]{2,16}*)+):?(d+)?/?#i", $string))

old code that looked for URL


if(empty($string) || preg_match("#^(http|https|ftp)://([A-Z0-9][A-Z0-9_-]*(?:.[A-Z0-9][A-Z0-9_-]*)+):?(d+)?/?#i", $string))

2 个解决方案



The problem is here:


[\w- ]{2,16}*

You can't use {2,16} and * together, you can only use one or the other.


If you were looking to match groups of 2 to 16 [\w- ]s, at least 0 times, wrap it in a subpattern and attach the * outside:

如果您希望匹配2到16 [\ w-]的組,至少0次,請將其包裝在子模式中並附加*外部:

(?:[\w- ]{2,16})*



What BoltClock says is correct. But there are other problems with your regex as well. First, to solve your immediate problem, here's a regex, which validates a username to be from 2 to 16 characters long consisting only of letters, digits, underscores, dashes/hyphens and spaces:


if (preg_match('/^[A-Za-z0-9_\- ]{2,16}$/', $string)) {
    // Valid username.

Note that there is no need for the 'empty() ||' clause because the regex matches only if there are at least 2 chars.


Second, regexes are very useful (and can even be fun!), but if you are going to use them, you need to sit down and learn the syntax, plain and simple (its not that hard). I would strongly recommend spending an hour or two studying the basics. There is an excellent online tutorial at: www.regular-expressions.info. The time you spend there will pay for itself many times over. Happy regexing!




粤ICP备14056181号  © 2014-2020 ITdaan.com