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

妖精的绣舞 提交于 2019-12-10 14:21:00

问题


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))

回答1:


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:

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



回答2:


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!



来源:https://stackoverflow.com/questions/5685238/warning-preg-match-function-preg-match-compilation-failed-nothing-to-repe

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!