Funky Syntax for validation

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
Steveo31
Forum Contributor
Posts: 416
Joined: Sun Nov 23, 2003 9:05 pm
Location: San Jose CA

Funky Syntax for validation

Post by Steveo31 »

I see this all over the place, and by doing some HW, I can understand some of it, but could someone elaborate to get a clearer view?

Code: Select all

/^[0-9]{5}([-]?[0-9]{4})?$/
I know it is

Numbers 0-9, only 5, a dash, numbers 0-9 again, only 4

But the end syntax and the format of the () is quirkin me.

_S
User avatar
Wayne
Forum Contributor
Posts: 339
Joined: Wed Jun 05, 2002 10:59 am

Post by Wayne »

everything in the () is a subpattern of the regular expression the ? means that it must match this pattern either 0 or 1 times, so
([-]?[0-9]{4})? ... means that it must match the - 0 or 1 times followed by 4 digits of 0-9. with that whole subpattern being match 0 or 1 times, the $ at the very end means that there is nothing after.
Steveo31
Forum Contributor
Posts: 416
Joined: Sun Nov 23, 2003 9:05 pm
Location: San Jose CA

Post by Steveo31 »

Ah nice. Thanks for diggin :)
Post Reply