I need to check the U.K postcode against a list.
The U.K postcode is of a standard format but the list only contains the outward section that I need to check against.
The list contains a series of outward postcode with also some data relating to this outward postcode, so for example
AL St Albans
B Birmingham
BT Belfast
TR Taunton
TR21 Taunton X
TR22 Taunton Y
My aim is that when I get a postcode, for example B20 7TP, I can search and find Birmingham.
Any ideas??
The question is different to the ones referred to as possible answers, but in my case I need to check a full postcode against just the outward postcode.
If you have the whole postcode and only want to use the outcode, remove the last three characters and use what remains. All postcodes end with the pattern digit-alpha-alpha, so removing those characters will give the outcode; any string that does not fit that pattern or that does not give a valid outcode after removing that substring is not a valid postcode. (Source)
If you're willing to take on an external (and Internet-based) dependency, you could look at using something like https://postcodes.io, in particular the outcodes section of that API. I have no affiliation with postcodes.io; I just found it after a Google.
Per the documentation, /outcodes will return
For reference, a call to /outcodes/TA1 returns:
{
"status": 200,
"result": {
"outcode": "TA1",
"longitude": -3.10297767924529,
"latitude": 51.0133987332761,
"northings": 124359,
"eastings": 322721,
"admin_district": [
"Taunton Deane"
],
"parish": [
"Taunton Deane, unparished area",
"Bishop's Hull",
"West Monkton",
"Trull",
"Comeytrowe"
],
"admin_county": [
"Somerset"
],
"admin_ward": [
"Taunton Halcon",
"Bishop's Hull",
"Taunton Lyngford",
"Taunton Eastgate",
"West Monkton",
"Taunton Manor and Wilton",
"Taunton Fairwater",
"Taunton Killams and Mountfield",
"Trull",
"Comeytrowe",
"Taunton Blackbrook and Holway"
],
"country": [
"England"
]
}
}
If you have the whole postcode, the /postcodes endpoint will return considerably more detailed information which I will not include here, but it does include the outcode and the incode as separate fields.
I would, of course, recommend caching the results of any call to a remote API.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With