function isPostCode($countryCode, $postalCode) { switch($countryCode) { case 'US': $pattern = "/^\d{5}$/i"; //US postal code pattern break; case 'CA': $pattern = "/^[A-Z]\d[A-Z] \d[A-Z]\d$/i"; //Canadian postal code pattern break; case 'UK': $pattern = "/^[A-Z]{1,2}\d{1,2}[A-Z]?\s\d[A-Z]{2}$/i"; //UK postal code pattern break; default: return false; //invalid country code } return preg_match($pattern, $postalCode); //compares pattern with the input postal code }
isPostCode('US', '12345'); //returns true
isPostCode('CA', 'V7H 1C5'); //returns true
isPostCode('UK', 'SW1A 2AA'); //returns truePackage Library: This function does not belong to any particular PHP library, it can be used as a standalone function in any PHP project.