Posted By

naz on 03/17/08


Tagged

regex php array postcode


Versions (?)

Who likes this?

2 people have marked this snippet as a favorite

naz
silentbob84


UK postcode parser


 / Published in: PHP
 

This function can validate and parse UK postcode like SW1A 1AA in to formated array.

  1. function parseUkPostcode($postcode) {
  2.  
  3. $postcode = strtoupper(ereg_replace("[^A-Za-z0-9]", "", trim($postcode)));
  4.  
  5. $lenght = strlen($postcode);
  6.  
  7. if($lenght < 5 OR $lenght == 4){
  8.  
  9. $regex = '/^([A-Z]{1,2})([0-9][0-9A-Z]?)$/';
  10.  
  11. if (preg_match($regex, $postcode, $part)) {
  12.  
  13. $code = array(
  14. 'full' => $part[1] . $part[2],
  15. 'area' => $part[1],
  16. 'district' => $part[2],
  17. 'outer' => $part[1] . $part[2],
  18. 'sector' => NULL,
  19. 'walk' => NULL,
  20. 'inner' => NULL
  21. );
  22.  
  23. }else{
  24.  
  25. $code = NULL;
  26.  
  27. }
  28.  
  29. }else{
  30.  
  31. $regex = '/^([A-Z]{1,2})([0-9][0-9A-Z]?)\s*([0-9])([A-Z]{2})$/';
  32.  
  33. if (preg_match($regex, $postcode, $part)) {
  34.  
  35. $code = array(
  36. 'full' => $part[1].$part[2].' '.$part[3].$part[4],
  37. 'area' => $part[1],
  38. 'district' => $part[2],
  39. 'outer' => $part[1] . $part[2],
  40. 'sector' => $part[3],
  41. 'walk' => $part[4],
  42. 'inner' => $part[3] . $part[4]
  43. );
  44.  
  45. }else{
  46.  
  47. $code = NULL;
  48.  
  49. }
  50. }
  51. return $code;
  52. }

Report this snippet  

You need to login to post a comment.