Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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))
like image 826
acctman Avatar asked Apr 16 '11 07:04

acctman


2 Answers

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})*
like image 72
BoltClock Avatar answered Oct 16 '22 07:10

BoltClock


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!

like image 30
ridgerunner Avatar answered Oct 16 '22 07:10

ridgerunner