0

Hi i need to extract to the postcode sector from a full postcode.

See below for to see how i need this to return.

User inputs "BA12 3GH"  Script Returns >> "BA12"
User inputs "H2 3NM"  Script Returns >> "H2"
David Allen
  • 1,123
  • 2
  • 10
  • 24
  • To be slightly pedantic, what you are referring to as the Sector is actually the District. The sector would be everything except the last two characters. - http://www.alliescomputing.com/innovation/glossary – Stephen Keable Jan 14 '15 at 09:51

2 Answers2

1
$postcode = 'BA12 3GH';
// If you want both parts, do list($sector, $otherpart) = ...
list($sector) = explode(' ', $postcode);
echo $sector;

(you should add , 2 in the explode if you want to extract both parts, so if the inputs AA BB CC then $otherpart becomes BB CC)

Jay
  • 3,285
  • 1
  • 20
  • 19
0

To make things better, you need to understand the format of a postcode, which consists of outcode and incode. for instance, "BA12 3GH", BA12 is the outcode and 3GH is incode. The outcode can be 2-4 chars, such as B1, EH16. However, the incode always is three chars, starts with a digit, and followed with two chars. For more information about the format rules: http://www.ukpostcode.net/uk-postcodes-formatting-rules-wiki-6.html

Thus, it will become very clear.

$sector = trim(substr($postcode,0,-3));

Scripts above will also work when user input postcode without space between outcode and incode.

James Duan
  • 39
  • 2