Alex Poole

Pragmatic PHP, MySQL, Marketing & Technology

Alex Poole header image 2

Split UK postcodes in PHP

April 29th, 2008 by alex

Found this useful function for splitting postcodes in Python.

http://www.brunningonline.net/simon/blog/archives/001292.html

Needed something similar in PHP, so:

$tests = Array('cr0 2yr' , //('CR0', '2YR')),'cr02yr' , //('CR0', '2YR')), 

'dn16 9aa' , //('DN16', '9AA')), 

'dn169aa' , //('DN16', '9AA')), 

'ec1a 1hq' , //('EC1A', '1HQ')), 

'ec1a1hq' , //('EC1A', '1HQ')), 

'm2 5bq' , //('M2' , '5BQ')), 

'm25bq' , //('M2' , '5BQ')), 

'm34 4ab' , //('M34' , '4AB')), 

'm344ab' , //('M34' , '4AB')), 

'sw19 2et' , //('SW19', '2ET')), 

'sw192et' , //('SW19', '2ET')), 

'w1a 4zz' , //('W1A' , '4ZZ')), 

'w1a4zz' , //('W1A' , '4ZZ')), 

'cr0' , //('CR0' , '' )), 

'sw19' , 

'ec1v 74v' 

); 

function splitpostcode($postcode){ 

 $postcode = strtoupper(str_replace(" ", "", trim($postcode))); 

 if (strlen($postcode) <= 4) return Array($postcode, ''); 

 return Array(substr($postcode, 0, -3), substr($postcode, -3)); 

} 

foreach($tests AS $row){ 

 echo "<b>".$row.">/b<"; 

 print_r(splitpostcode($row)); 

 echo "<br>"; 

} 

 

No validation here obviously, but I hope you find this useful..

Tags: 1 Comment

Leave a Comment

1 response so far ↓

  • Thanks for the code Alex.
    I am a novice at php and had this postcode issue as a task to solve.
    Incidentally you have “>/b<” where it should be “”
    Still a novice and still dont understand how to just display the postcode elements without the array references. I would assume it is something to do with referring to the array subscripts 0 and 1
    Feel free to e-mail me the answer. he he
    Si