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

我正在嘗試將urg檢查中的preg_match檢查更改為用戶名檢查,這是最小/最大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

尋找網址的舊代碼

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

2 个解决方案

#1


8  

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

#2


0  

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。你在那里度過的時間會多次為自己付出代價。快樂regexing!


注意!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系我们删除。



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