Page 1 of 1

eregi, not sure why canadian postal code doesn't match

Posted: Wed Mar 26, 2008 2:36 pm
by kryles
Hi,

Im trying to use regular expressions to test Canadian Postal Codes. For those unfamiliar these are the approved formats (at least for me :P)

h9h 9h9
h9h9h9
h9h-9h9

this is what I tried to use

Code: Select all

 
if($safeZip == "")
{
    $errMsg .= "Postal Code is required. Make sure it is not left blank<br />";
}
elseif((strlen($safeZip) != 7) && (strlen($safeZip) != 6))
{
    $errMsg .= "Invalid Postal Code<br />";
}
elseif(!eregi("^[a-zA-Z][0-9][a-zA-Z](\s|-)?[0-9][a-zA-Z][0-9]$", $safeZip))
{
    $errMsg .= "Invalid Postal Code<br />";
}
 
Should this work? Thanks

Re: eregi, not sure why canadian postal code doesn't match

Posted: Wed Mar 26, 2008 3:02 pm
by John Cartwright
ereg is deprecated, therefore you use be using preg_* anyways

Code: Select all

preg_match('#[a-z]\d[a-z][\s-]*\d[a-z]\d#i', ..);

Re: eregi, not sure why canadian postal code doesn't match

Posted: Wed Mar 26, 2008 4:07 pm
by kryles
Okay so I changed to preg_match which seems to work also (I figured out my original mistake).

Code: Select all

 
elseif(!preg_match('#[a-z]\d[a-z][\s-]?\d[a-z]\d#i', $safeZip))
{
    $errMsg .= "Invalid Postal Code<br />";
}
 
only change I made (which is irrelevant since I test string length anyways) is I use the '?' instead if the '*'.

Thanks!