Extracting first part of a post code

Any questions involving matching text strings to patterns - the pattern is called a "regular expression."

Moderator: General Moderators

Post Reply
mzfp2
Forum Contributor
Posts: 137
Joined: Mon Nov 11, 2002 9:44 am
Location: UK
Contact:

Extracting first part of a post code

Post 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
timvw
DevNet Master
Posts: 4897
Joined: Mon Jan 19, 2004 11:11 pm
Location: Leuven, Belgium

Post by timvw »

So you want to get everything untill the first space? Because in that case you can use strpos and substr...
printf
Forum Contributor
Posts: 173
Joined: Wed Jan 12, 2005 5:24 pm

Post 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!
ntbd
Forum Newbie
Posts: 21
Joined: Wed Apr 12, 2006 6:42 am

Post 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.
User avatar
pickle
Briney Mod
Posts: 6445
Joined: Mon Jan 19, 2004 6:11 pm
Location: 53.01N x 112.48W
Contact:

Post 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.
Real programmers don't comment their code. If it was hard to write, it should be hard to understand.
Post Reply