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
Extracting first part of a post code
Moderator: General Moderators
You can use preg_match....
Here is a simple validation example
pif!
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!