Steve Price Steve Price - 1 year ago 42
PHP Question

How to collect just the first 1 or 2 characters of a postcode using php

I found this useful function here on SO, but I need it to work slightly differently. I have to take JUST the first two characters of the postcode, without any of the numbers so that they can be used to compare against a table that hold postcode prefixes and regions. Searching this database with CH7 would not return any results as the database contains only CH.

function getUKPostcodeFirstPart($postcode)
// validate input parameters
$postcode = strtoupper($postcode);

// UK mainland / Channel Islands (simplified version, since we do not require to validate it)
if (preg_match('/^[A-Z]([A-Z]?\d(\d|[A-Z])?|\d[A-Z]?)\s*?\d[A-Z][A-Z]$/i', $postcode))
return preg_replace('/^([A-Z]([A-Z]?\d(\d|[A-Z])?|\d[A-Z]?))\s*?(\d[A-Z][A-Z])$/i', '$1', $postcode);
// British Forces
if (preg_match('/^(BFPO)\s*?(\d{1,4})$/i', $postcode))
return preg_replace('/^(BFPO)\s*?(\d{1,4})$/i', '$1', $postcode);
// overseas territories
if (preg_match('/^(ASCN|BBND|BIQQ|FIQQ|PCRN|SIQQ|STHL|TDCU|TKCA)\s*?(1ZZ)$/i', $postcode))
return preg_replace('/^([A-Z]{4})\s*?(1ZZ)$/i', '$1', $postcode);

// well ... even other form of postcode... return it as is
return $postcode;

If I test this using the following

$postcode ="CH7 3DT";
echo 'CH7 3DT -> ', getUKPostcodeFirstPart($postcode), "\n";

I get a result of CH7, which exactly what the code is supposed to do. But I need to have a return of just CH

B31 5SN should return just B,
SY4 4RG should return just SY

I've tried removing various parts of the preg_replace to reduce the output but I either get nothing, or the full postcode again.
To be honest, preg_replace is so confusing to me!

Answer Source
preg_replace("/[^A-Za-z]/", "", getUKPostcodeFirstPart($postcode);

This should replace any non-alphabet characters with nothing, essentially stripping them from the string.