Regex: Postal Codes

Small, short code snippets that other people may find useful. Do you have a good regex that you would like to share? Share it! Even better, the code can be commented on, and improved.

Moderator: General Moderators

Post Reply
jason
Site Admin
Posts: 1767
Joined: Thu Apr 18, 2002 3:14 pm
Location: Montreal, CA
Contact:

Regex: Postal Codes

Post by jason »

Using the preg_* functions:

USA

Code: Select all

'/^\d{5}(-\d{4})?$/'
Canadian

Code: Select all

'/^їa-z]\dїa-z] ?\dїa-z]\d$/i'
Example:

Code: Select all

<?php

if ( preg_match('/^\d{5}(-\d{4})?$/', '55082') ) {
	echo 'yes';
} else {
	echo 'no';
}

if ( preg_match('/^[a-z]\d[a-z] ?\d[a-z]\d$/i', 'H1S 1T6') ) {
	echo 'yes';
} else {
	echo 'no';
}

?>
If you have Pregular Expressions for other countries, list those as here, as well.
User avatar
volka
DevNet Evangelist
Posts: 8391
Joined: Tue May 07, 2002 9:48 am
Location: Berlin, ger

Post by volka »

german zip codes simply consist of five digits

Code: Select all

/^\d&#123;5&#125;$/
User avatar
twigletmac
Her Royal Site Adminness
Posts: 5371
Joined: Tue Apr 23, 2002 2:21 am
Location: Essex, UK

Post by twigletmac »

British, will match BA12 3PR type post codes, as well as inner London type ones (EC1M 3AA) and the space is optional:

Code: Select all

/^&#1111;a-z]&#123;1,2&#125;\d&#123;1,2&#125;&#1111;a-z]? ?\d&#1111;a-z]&#123;2&#125;$/i
Mac
User avatar
AVATAr
Forum Regular
Posts: 524
Joined: Tue Jul 16, 2002 4:19 pm
Location: Uruguay -- Montevideo
Contact:

Post by AVATAr »

Uruguayan zip codes, the same as german, five digits

Code: Select all

/^\d&#123;5&#125;$/
User avatar
JAM
DevNet Resident
Posts: 2101
Joined: Fri Aug 08, 2003 6:53 pm
Location: Sweden
Contact:

Post by JAM »

Swedish, 5 digits, optional space after the first 3.

Code: Select all

/^\d&#123;3&#125;? ?\d&#123;2&#125;$/
User avatar
n00b Saibot
DevNet Resident
Posts: 1452
Joined: Fri Dec 24, 2004 2:59 am
Location: Lucknow, UP, India
Contact:

Post by n00b Saibot »

India ones are simple 6 digits long.

Code: Select all

/^\d&#123;6&#125;$/
Post Reply