php 警告:preg_match() [function.preg-match]:编译失败:在偏移处没有重复
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5685238/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Warning: preg_match() [function.preg-match]: Compilation failed: nothing to repeat at offset
提问by acctman
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
我正在尝试将 preg_match 检查从 url 检查更改为用户名检查,最小/最大 2-16chrs、破折号、空格和连字符是可以接受的。我收到这个错误
Warning:preg_match() [function.preg-match]: Compilation failed: nothing to repeat at offset 14
警告:preg_match() [function.preg-match]:编译失败:在偏移 14 处无需重复
if(empty($string) || preg_match("#^([\w- ]{2,16}*(?:.[\w- ]{2,16}*)+):?(d+)?/?#i", $string))
old code that looked for URL
寻找 URL 的旧代码
if(empty($string) || preg_match("#^(http|https|ftp)://([A-Z0-9][A-Z0-9_-]*(?:.[A-Z0-9][A-Z0-9_-]*)+):?(d+)?/?#i", $string))
回答by BoltClock
The problem is here:
问题在这里:
[\w- ]{2,16}*
You can't use {2,16}
and *
together, you can only use one or the other.
不能{2,16}
和和*
一起使用,只能使用其中之一。
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})*
回答by ridgerunner
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:
BoltClock 所说的是正确的。但是您的正则表达式也存在其他问题。首先,为了解决您的直接问题,这里有一个正则表达式,它验证用户名的长度为 2 到 16 个字符,仅包含字母、数字、下划线、破折号/连字符和空格:
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.
请注意,不需要该'empty() ||'
子句,因为正则表达式仅在至少有 2 个字符时才匹配。
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!
其次,正则表达式非常有用(甚至可以很有趣!),但是如果您要使用它们,则需要坐下来学习语法,简单明了(并不难)。我强烈建议花一两个小时学习基础知识。有一个很好的在线教程:www.regular-expressions.info。你在那里度过的时间会物有所值。快乐的正则表达式!