PHP Logo

For the last couple of years, I’ve been mostly doing PHP coding. As a result, I have small library of code snippets of my own. Those are simple but useful PHP codes that might save some time on your work!

First one I’m sharing here today is the combination of regular expression and the PHP code to do ZIP code (or Postal Code) validation for following 12 countries: United States of America, United Kingdom, Germany, Canada, France, Italy, Australia, Netherlands, Spain, Denmark, Sweden & Belgium.

Code is provided in PHP but the REGEX codes are universal and those can be used with other programming languages.

License

This code is free to use, distribute, modify and study. When referencing please link back to this website / post in any way e.g. direct link, credits etc. If you find this useful, please leave a comment and share using the buttons below!

<?php
$country_code="US";
$zip_postal="11111";
 
$ZIPREG=array(
	"US"=>"^\d{5}([\-]?\d{4})?$",
	"UK"=>"^(GIR|[A-Z]\d[A-Z\d]??|[A-Z]{2}\d[A-Z\d]??)[ ]??(\d[A-Z]{2})$",
	"DE"=>"\b((?:0[1-46-9]\d{3})|(?:[1-357-9]\d{4})|(?:[4][0-24-9]\d{3})|(?:[6][013-9]\d{3}))\b",
	"CA"=>"^([ABCEGHJKLMNPRSTVXY]\d[ABCEGHJKLMNPRSTVWXYZ])\ {0,1}(\d[ABCEGHJKLMNPRSTVWXYZ]\d)$",
	"FR"=>"^(F-)?((2[A|B])|[0-9]{2})[0-9]{3}$",
	"IT"=>"^(V-|I-)?[0-9]{5}$",
	"AU"=>"^(0[289][0-9]{2})|([1345689][0-9]{3})|(2[0-8][0-9]{2})|(290[0-9])|(291[0-4])|(7[0-4][0-9]{2})|(7[8-9][0-9]{2})$",
	"NL"=>"^[1-9][0-9]{3}\s?([a-zA-Z]{2})?$",
	"ES"=>"^([1-9]{2}|[0-9][1-9]|[1-9][0-9])[0-9]{3}$",
	"DK"=>"^([D-d][K-k])?( |-)?[1-9]{1}[0-9]{3}$",
	"SE"=>"^(s-|S-){0,1}[0-9]{3}\s?[0-9]{2}$",
	"BE"=>"^[1-9]{1}[0-9]{3}$"
);
 
if ($ZIPREG[$country_code]) {
 
	if (!preg_match("/".$ZIPREG[$country_code]."/i",$zip_postal)){
		//Validation failed, provided zip/postal code is not valid.
	} else {
		//Validation passed, provided zip/postal code is valid.
	}
 
} else {
 
	//Validation not available
 
}
?>

Share this

4 Responses to “ZIP (POSTAL) Code Validation Regex & PHP code for 12 Countries”

Add Comment
  1. {1] is useless…

    and it depends of the data you read ^blablabla$
    is useless too.

    US formula is also accepting 12345-

    Did not check more than a quick shot…

  2. This `if ($ZIPREG[$country_code])` will generate a ‘Notice’ if an unsupported country is provided. Better to use `if (isset($ZIPREG[$country_code])` instead.

  3. Will this work for: “enter your zip to see if we deliver to your area”

Leave a Reply