PHP Find first part of UK postcode when full or part can be entered

php

Solution

IMHO regexes are exactly the right solution to the problem.

Ignoring for now BFPO address, try:

if (preg_match("(([A-Z]{1,2}[0-9]{1,2})($|[ 0-9]))", trim($postcode), $match)) {
   $region=$match[1];
}

Problem

Someone please put me out of my misery and help me solve this one. I have a postcode lookup box that allows people to put in full postcodes (e.g. BS34 5GF) or part post codes (e.g. BS34). My postcode lookup only requires the first part of the postcode and I am trying to find the most effective way of trimming the string to only have the first section, without explicitly knowing the format it is entered in. Here are some example codes: B2 5GG, B22 5GG, BS22 5GG, B25GG, BS25GG, BS225GG, B2, BS2, BS22 This shows how many possible variations there could be.. What is the best way to ensure I always get the first part of the postcode?

Original source

Related problems