Page 1 of 1

Extracting first part of a post code

Posted: Sun Apr 02, 2006 6:07 am
by mzfp2
Hi, im working with UK postcodes, and need to validate postcodes being entered into the system, postcodes are usually in the following format

BB3 5TT

I need to extract the first part of the postcode, which are letters then numbers, and come in the following foormat :

BB3 or
BB10 or
B3 or
B10

The above shows sometimes it is a pair of letters thhen a number (one or two digits), or just a letter then a number (again one or two digits)

How would I go about extracting this information from the original postcode in reg exp?

Thanks in advanvce

Posted: Sun Apr 02, 2006 8:58 am
by timvw
So you want to get everything untill the first space? Because in that case you can use strpos and substr...

Posted: Wed Apr 12, 2006 9:40 am
by printf
You can use preg_match....

Code: Select all

preg_match ( "|^([a-z]{1,2}[0-9]{1,2})\s?([a-z]{0,1}[0-9]{1}[a-z]{2})$|i", $code, $match );

// first part
echo $match[1] . "<br />";

// second part
echo $match[2] . "<br />";

Here is a simple validation example

Code: Select all

<?

$code = array ( 
'', 
'B', 
'1', 
'BT', 
'11', 
'BT1', 
'B1F1 5NG', 
'BT6888', 
'BT100 5RT', 
'WCF 200', 
'BT6 8CI', 
'W1 3NT', 
'E178pr', 
'BT6 2NG', 
'Bt23 1NG', 
'N1C8UH', 
'ne6 9Rw', 
'BPO1PS' 
);

for ( $i = 0; $i < sizeof ( $code ); $i++ )
{
	if ( ! preg_match ( "|^([a-z]{1,2}[0-9]{1,2})\s?([a-z]{0,1}[0-9]{1}[a-z]{2})$|i", $code[$i], $match ) )
	{
		echo "Not Valid " . $i . ": " . $code[$i] . "\r\n<br />\r\n";
	}
	else
	{
		echo "Match Start -> " . $match[1] . ", Match End -> " . $match[2] . "\r\n<br />\r\n";
	}
}

?>

pif!

Posted: Wed Apr 12, 2006 12:32 pm
by ntbd
Dont expect users to enter a space though.

Valid codes could be...

AB43RY
CD289BZ

So your going to have to work with numbers rather than characters. Dont know what that changes. 0-99 wouldnt be valid i asume.

Posted: Wed Apr 12, 2006 1:55 pm
by pickle
If the postal codes have two parts, with the first being 3 or 4 characters and the second always being 3 - stripping off the last 3 characters should give you the first part.