Forum Moderators: coopster

Message Too Old, No Replies

stupid square brackets in php regex won't work!

         

jonasisme

6:45 pm on Sep 11, 2011 (gmt 0)

10+ Year Member



Hi people.. i need to match aA-zZ, 0-9, _ and - and [ and ]

However everything works except [ and ]

this is what i got:

preg_match("/^[a-zA-Z0-9_-]+$/", $_POST['field']);


Please help me out as I can't find the solution!


Thanks in advance

g1smd

7:15 pm on Sep 11, 2011 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member Top Contributors Of The Month



The [ and ] need to be escaped.

"/^[a-zA-Z0-9\[\]_-]+$/"

jonasisme

7:31 pm on Sep 11, 2011 (gmt 0)

10+ Year Member



omfg.. i had that, i tried that 1000 times.. but i had put the brackets on the end.. like this "/^[a-zA-Z0-9_-\[\]]+$/" that's why it was working..

Thank you very much! Solved!

g1smd

7:40 pm on Sep 11, 2011 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member Top Contributors Of The Month



It should also work with the brackets at the very end.

I moved them merely to show more clearly the required escaping. The \[\]] format makes my eyes boggle and \[\]_-] is more clear.

Also, some RegEx parsers like the hyphen to be the very last item in the list otherwise they get confused.

lucy24

8:57 pm on Sep 11, 2011 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member Top Contributors Of The Month



Also, some RegEx parsers like the hyphen to be the very last item in the list otherwise they get confused.

... while others will only recognize it as a literal hyphen if it's the first item in the list ;) Literal carets, otoh, can't come first unless they are escaped. (I only know this because I've got a RegEx reference page open from another thread. Fortunately, grouping brackets tend not to get upset if you follow the "when in doubt, escape it" principle.)

rocknbil

4:17 pm on Sep 12, 2011 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



Since no one's mentioned why, square brackets designate a character class. when you want to match bracket within character class, this is why it needs to be escaped.

FYI, this

preg_match("/^[a-zA-Z0-9\[\]_-]+$/", $_POST['field']);

is equivalent to this, with the i (case insensitive modifier.

preg_match("/^[a-z\d\[\]_-]+$/i", $_POST['field']);

\d being any digit.

g1smd

6:11 pm on Sep 12, 2011 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member Top Contributors Of The Month



You can only use \d if your server can use PCRE.

I usually post using POSIX format, as that is more likely to work across a range of servers. If PCRE does work, it is somewhat more efficient.