RE: [PHP] Zip to postcode[Scanned]
| From: | Ford, Mike [LSS] | Date: | Wed, 02 Apr 2003 13:00:59 +0000 |
| Subject: | RE: [PHP] Zip to postcode[Scanned] | ||
| Groups: | php.general | ||
| Request: | Send a blank email to php-general+get-141977@lists.php.net to get a copy of this message | ||
> -----Original Message-----
> From: Michael Egan [mailto:MEgan@3tc.org.uk]
> Sent: 02 April 2003 13:05
>
> There are some ready made scripts for dealing with UK post
> codes on the relevant page on the PHP site:
>
> http://www.php.net/manual/en/function.ereg.php
And not one of them is 100% correct!! This would be my stab:
preg_match('/^([A-Z]{1,2}([0-9]{1,2})|[0-9][A-Z])|GIR)'
. ' ?[0-9][A-Z]{2}$/i', $postcode)
(I've divided the pattern in two here simply to avoid strange line wrapping!)
One of the user notes referred to says that postcodes are sometimes written with a space after the
initial letters; although technically this is incorrect, adjusting to allow it would give:
preg_match('/^([A-Z]{1,2} ?([0-9]{1,2})|[0-9][A-Z])|GIR)'
. ' ?[0-9][A-Z]{2}$/i', $postcode)
Another states that the set of letters in the last two positions is restricted -- I can't vouch
for the accuracy of this, but if it's the case the match would become:
preg_match('/^([A-Z]{1,2} ?([0-9]{1,2})|[0-9][A-Z])|GIR)'
. ' ?[0-9]}[ABD-HJLNP-UW-Z]{2}$/i', $postcode)
Finally, if you really, really want to accept only completely valid postcodes (not just validly
formatted ones), you should get the full list of postcode area identifiers (the initial letter or
two) and validate against those -- plus any local peculiarities that occur (for example, in my local
postcode area, the final digit is 2 in *all* cases). (Well, I guess here we're getting into
the realms of paying for the Royal Mail's postcode database!!)
Cheers!
Mike
---------------------------------------------------------------------
Mike Ford, Electronic Information Services Adviser,
Learning Support Services, Learning & Information Services,
JG125, James Graham Building, Leeds Metropolitan University,
Beckett Park, LEEDS, LS6 3QS, United Kingdom
Email: m.ford@lmu.ac.uk
Tel: +44 113 283 2600 extn 4730 Fax: +44 113 283 3211