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
kryles
Forum Contributor
Posts: 114 Joined: Fri Feb 01, 2008 7:52 am
Post
by kryles » Wed Mar 26, 2008 2:36 pm
Hi,
Im trying to use regular expressions to test Canadian Postal Codes. For those unfamiliar these are the approved formats (at least for me
)
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
John Cartwright
Site Admin
Posts: 11470 Joined: Tue Dec 23, 2003 2:10 am
Location: Toronto
Contact:
Post
by John Cartwright » Wed Mar 26, 2008 3:02 pm
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
Post
by kryles » Wed Mar 26, 2008 4:07 pm
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!