PHP UK postcode regex

Hi Guys!

I found this regex on the net, but I need to modify it so that it supports postcodes without spaces (i.e. IG57DH). At the moment it will only support postcodes with spaces (i.e. IG5 7DH).


function ValidatePostcode($string)
	{
		$postcode = strtoupper($string);
		if(!ereg("((GIR 0AA)|(TDCU 1ZZ)|(ASCN 1ZZ)|(BIQQ 1ZZ)|(BBND 1ZZ)"
		."|(FIQQ 1ZZ)|(PCRN 1ZZ)|(STHL 1ZZ)|(SIQQ 1ZZ)|(TKCA 1ZZ)"
		."|[A-PR-UWYZ]([0-9]{1,2}|([A-HK-Y][0-9]"
		."|[A-HK-Y][0-9]([0-9]|[ABEHMNPRV-Y]))"
		."|[0-9][A-HJKS-UW]) [0-9][ABD-HJLNP-UW-Z]{2})", $postcode))
		{
			return false;
		} else
		{
			return true;	
		}
	}

Is this possible?

For what it’s worth, there are a bunch of postcodes starting N1P that won’t be deemed “valid”.

Oh - and another thing, str_replace(“O”,“0”, $incoming); Many ppl think the zero in their postcode is a letter “Oh”.

You could always pipe the request straight to uk-postcodes.com then you can benefit from not only knowing it is well formed, but also exists.

UK Postcodes | Data for NE1 1AA

My cursory glance tells me it it parses out the space and uppercases it, so to speed things at their end, strtoupper(), trim(), str_replace() the space, check result is between 5 and 9(?) chars long - then send to this service and the result can tell you if the Postcode exists.

Probably more useful if you are actually going to go on and make some decisions based upon locality.

Positive result retrieves: Pcode, lat, lng, East, North, shortened url, City or district, Ward.


        NE1 1AA
        54.967724
	-1.615771
	424696
	563745
	http://geohash.org/gcybenx6jy3v
	Newcastle upon Tyne
        Westgate

Any of that add value to your proposition?

Thanks for your help guys, I should be able to implement both of these solutions!

Thank you.


<?php
error_reporting(-1);
ini_set('display_errors', true);

function ValidatePostcode($postcode)
{
  return (bool)preg_match(
    "~^(GIR 0AA)|(TDCU 1ZZ)|(ASCN 1ZZ)|(BIQQ 1ZZ)|(BBND 1ZZ)"
  . "|(FIQQ 1ZZ)|(PCRN 1ZZ)|(STHL 1ZZ)|(SIQQ 1ZZ)|(TKCA 1ZZ)"
  . "|[A-PR-UWYZ]([0-9]{1,2}|([A-HK-Y][0-9]"
  . "|[A-HK-Y][0-9]([0-9]|[ABEHMNPRV-Y]))"
  . "|[0-9][A-HJKS-UW])\\s?[0-9][ABD-HJLNP-UW-Z]{2}$~i",
  $postcode);
}

var_dump(
  ValidatePostcode('NE11AA')
);

var_dump(
  ValidatePostcode('NE1 1AA')
);

var_dump(
  ValidatePostcode('ne11aa')
);

var_dump(
  ValidatePostcode('ne1 1aa')
);

/*
  bool(true)
  bool(true)
  bool(true)
  bool(true)
*/