1

I have some text blocks like

John+and+Co-Accountants-Hove-BN31GE-2959519

I need a function to extract the postcode "BN31GE". It may happen to not exist and have a text block without postcode so the function must also validate if the extracted text is valid postcode .

John+and+Co-Accountants-Hove-2959519
Michael
  • 6,377
  • 14
  • 59
  • 91

3 Answers3

4

The UK Government Data Standard for postcodes is:

((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}))

Edit: I had the above in some (personal) code with a reference to a now non-existence UK government web page. The appropriate British Standard is BS7666 and information on this is currently available here. That lists a slightly different regex.

borrible
  • 17,120
  • 7
  • 53
  • 75
  • is not working . I think it's because in my text block the postcode doesn't have any space . – Michael Jun 20 '11 at 11:02
  • @Michael - if you change the " " to a " ?" (i.e. add a ? after the space towards the end of regex) you'll get something that optionally allows the space. – borrible Jun 20 '11 at 11:08
  • I added "?" but for some reasons still doesn't work. I've tried it agaist this text block "John+and+Co-Accountants-Hove-BN31GE-2959519" – Michael Jun 20 '11 at 11:14
  • @Michael - The above regex matches a UK postcode. You need to use it in the appropriate place in your wider regex. – borrible Jun 20 '11 at 12:04
2

Find below code to extract valid UK postal code. It return array if post code found otherwise empty.

<?php
$getPostcode="";
$str="John+and+Co-Accountants-Hove-BN31GE-2959519";
$getArray = explode("-",$str);
if(is_array($getArray) && count($getArray)>0) {
    foreach($getArray as $key=>$val) {
        if(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",strtoupper($val),$postcode)) {
            $getPostcode = $postcode[0];
        }
    }
}
print"<pre>";
print_r($getPostcode); 
?>
Sanjeev Chauhan
  • 3,977
  • 3
  • 24
  • 30
0

Use a regex: preg_grep function,

I don't know the format of english postcodes but you could go with something like:

(-[a-zA-Z0-9]+-)+

This matches

  • "-Accountants-"
  • "-BN31GE-"

You can then proceed at taking always the second value or you can enhance you regex to match exactly english postcodes, something like maybe

 ([A-Z0-9]{6})
OverLex
  • 2,501
  • 1
  • 24
  • 27