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

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
kryles
Forum Contributor
Posts: 114
Joined: Fri Feb 01, 2008 7:52 am

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

Post 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
User avatar
John Cartwright
Site Admin
Posts: 11470
Joined: Tue Dec 23, 2003 2:10 am
Location: Toronto
Contact:

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

Post 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', ..);
kryles
Forum Contributor
Posts: 114
Joined: Fri Feb 01, 2008 7:52 am

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

Post 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!
Post Reply