tags:

views:

111

answers:

2

Does any body know why the filter_var() function below is generating the warning? Is there a limit on how many characters can be in a character class?

$regex = "/^[\w\041\042\043\044\045\046\047\050\051\052\053\054\055\056\057\072\073\074\075\076\077\100\133\134\135\136\140\173\174\175\176]*$/";

$string = "abc";

if(!filter_var($string, FILTER_VALIDATE_REGEXP, array("options" => array("regexp"=>$regex))))
{
    echo "dirty";
}

else
{
    echo "clean";
}

Warning: filter_var() [function.filter-var]: Unknown modifier ':'

+2  A: 

Your regex is interpreted by PHP as this string :

string '/^[\w!"#$%&'()*+,-./:;<=>?@[\]^`{|}~]*$/' (length=40)

(use var_dump on $regex, and you'll get that)

Right in the middle of your regex, so, there is a slash ; as you are using a slash to delimit the regex (it's the first character of $regex), PHP thinks this slash in the middle is marking the end of the regex.

So, PHP thinks your regex is actually :

/^[\w!"#$%&'()*+,-./

Every character that comes after the ending slash are interpreted as modifiers.

And ':' is not a valid modifier.

You might want to escape the slash in the middle of the regex ;-)
As well as some other characters, btw...

A solution for that might be to use the preg_quote function.

Pascal MARTIN
Thank you for your help. It works now as I added backslashes using it's ASII code "134". I'll put the current regex in another answer right below.
lanmind
You're welcome :-) One question comes to my mind, though : why are you using ASCII codes, and not the characters directly ? It would be easier to understand your regex, that way, don't you think ?
Pascal MARTIN
I did think about that for about three seconds earlier, lol! The answer is that I used the space character's ANCII code in a regex before and since then the back of mind my tells me to do it for special characters. I'll likely change my way some day : )
lanmind
OK ^^ I understand a bit better, now ^^
Pascal MARTIN
A: 

Here is the current working regex:

/^[\w\041\042\043\044\045\046\047\050\051\052\053\054\134\055\056\134\057\072\073\074\075\076\077\100\133\134\134\134\135\134\136\140\173\174\175\176]*$/i
lanmind