Extract UK postcode from string

Hi guys

I need to extract the postcode from the address

I need to get to this

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

to this

$value="SW1A 0AA";‎

Many Thanks

Hi wazo,

You should be able to do that with a regular expression:


$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