Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Extract post code from an address string

Tags:

string

regex

php

I was wondering how to go about finding a postcode in an address string and making it its own variable using regex in .

for example $address = '123 My Street, My Area, My City, AA11 1AA'

I want $postcode = 'AA11 1AA'

I also want to remove the postcode that's found from the address string.

I have this so far.

$address = strtolower(preg_replace('/[^a-zA-Z0-9_ %\[\]\.\(\)%&-]/s', '', $data[2]));

$postcode = preg_match("/^(([A-PR-UW-Z]{1}[A-IK-Y]?)([0-9]?[A-HJKS-UW]?[ABEHMNPRVWXY]?|[0-9]?[0-9]?))\s?([0-9]{1}[ABD-HJLNP-UW-Z]{2})$/i",$address,$post);
$postcode = $post;
like image 315
Hemm K Avatar asked Feb 23 '26 00:02

Hemm K


1 Answers

This worked for me:

$value = "Big Ben, Westminster, London, SW1A 0AA, UK";

$pattern = "/((GIR 0AA)|((([A-PR-UWYZ][0-9][0-9]?)|(([A-PR-UWYZ][A-HK-Y][0-9][0-9]?)|(([A-PR-UWYZ][0-9][A-HJKSTUW])|([A-PR-UWYZ][A-HK-Y][0-9][ABEHMNPRVWXY])))) [0-9][ABD-HJLNP-UW-Z]{2}))/i";

preg_match($pattern, $value, $matches);

$value = $matches[0]; // Will give you SW1A 0AA

http://www.sitepoint.com/community/t/extract-uk-postcode-from-string/31962

like image 160
featherbelly Avatar answered Feb 25 '26 14:02

featherbelly



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!