Re: zip code validation/regular expression

From: Date: Mon, 02 Jun 2003 14:43:26 +0000
Subject: Re: zip code validation/regular expression
References: 1  Groups: php.general 
Request: Send a blank email to php-general+get-149802@lists.php.net to get a copy of this message
> Simply trying to use regular expressions to validate a 5 or 5+4 zip code, > excluding 00000 and 00000-0000. Looked on > http://www.regexlib.com, and > that's where I found the pattern below, but it doesn't work. The best I can > do on my own is two separate regular expressions, one to match a valid zip, > and another to match the 00000 invalid code. I would really like to > condense it into one, just because I think it should be possible. > This code below is suppose to do all this for me, but it's not matching as > I'd hoped. I get results like this: > > 21832-1234 MATCHES. > 00000-0000 MATCHES. > 00000 MATCHES. > 1234 doesn't match. > ABCDEF doesn't match. > ABC doesn't match. > > I'd appreciate any help. Thanks, > jason > > <?php > > $regex1 = "/^(\?(^00000(|-0000))|(\d{5}(|-\d{4})))$/"; > > $zips = > > array("21243","21832-1234","00000-0000","00000","1234","ABCDEF","ABC"); > > foreach ($zips as $zip) { > if (preg_match($regex1,$zip)) { > echo "$zip MATCHES.<br>"; > } else { > echo "$zip doesn't match.<br>"; > } > } > > ?> Don't know of a way to do it all in one regex. You could do something like this, though: $pattern = '/[0-9]{5}(-[0-9]{4})?/'; if((int)$zip && preg_match($pattern,$zip)) { echo "$zip MATCHES"; } else { echo "$zip doesn't match"; } Casting $zip to an INTEGER and checking for a TRUE value will eliminate 00000, 00000-0000, and anything starting with a letter right off the bat. Then your regex can handle the rest. ---John Holmes...

« previous php.general (#149802) next »