Re: Zip Codes ctype? Pregmatch? [message #182649 is a reply to message #182648] |
Wed, 21 August 2013 12:58 |
Thomas 'PointedEars'
Messages: 701 Registered: October 2010
Karma:
|
Senior Member |
|
|
Thomas 'PointedEars' Lahn wrote:
> Norman Peelman wrote:
>> On 08/20/2013 01:27 PM, Twayne wrote:
>>> I'm attempting to check for US and Canadian zip codes (postal codes).
>>> The US is easy; mostly just be sure it's five numerics and except
>>> "00000" and "99999". […]
>>
>> US Zip code:
>> [0-9]{5}(-{0,1}[0-9]{4}){0,1}
> ^^^^^ ^^^^^^^^^^ ^^^^^
> In Perl-Compatible Regular Expressions (PCRE), as also used by PHP's
> preg_* functions, the following shorthands are available:
>
> - “*” for “{0,}”
> - “?” for “{0,1}”
> - “+” for “{1,}”
> - “\d” for “[0-9]” (includes more numeric characters in “UTF-8 mode”)
>
> Thus, the above expression can be simplified to
>
> \d{5}(-?\d{4})?
>
> However, the specification above says that “00000” and “99999” are _not_
> valid U.S. ZIP codes, so to be exact you cannot just use either “[0-9]{5}”
> or “\d{5}”; but you would have to use, for example, a zero-width negative
> lookahead:
>
> $possibleZips = array('00000', '00001', '99998', '99999');
> foreach ($possibleZips as $possibleZip)
> {
> preg_match('^(?![09]{5})\\d{5}(?:-?\\d{4})?$', $possibleZip,
Replace this line with
preg_match('/^(?![09]{5})\\d{5}(?:-?\\d{4})?$/', $possibleZip,
(add the delimiter).
> $matches);
> var_dump($possibleZip);
> var_dump($matches);
> }
>
> (thanks to Anubhava: <http://stackoverflow.com/a/9609624/855543>)
--
PointedEars
|
|
|