PHPackages                             detain/zip-zapper - PHPackages - PHPackages  [Skip to content](#main-content)[PHPackages](/)[Directory](/)[Categories](/categories)[Trending](/trending)[Leaderboard](/leaderboard)[Changelog](/changelog)[Analyze](/analyze)[Collections](/collections)[Log in](/login)[Sign up](/register)

1. [Directory](/)
2. /
3. [API Development](/categories/api)
4. /
5. detain/zip-zapper

ActiveLibrary[API Development](/categories/api)

detain/zip-zapper
=================

Validates Zip/Postal Codes for any country and provides each country's localized name for their version of the Zip/Postal code (CEP, PLZ, PIN code, Eircode, NPA, CAP, ZIP code, etc.).

v2.0.0(6y ago)83.1k4MITPHPPHP &gt;=5.4CI failing

Since Mar 22Pushed 1mo agoCompare

[ Source](https://github.com/detain/zip-zapper)[ Packagist](https://packagist.org/packages/detain/zip-zapper)[ Docs](https://detain.github.io/zip-zapper)[ RSS](/packages/detain-zip-zapper/feed)WikiDiscussions master Synced today

READMEChangelog (3)Dependencies (1)Versions (5)Used By (0)

Zip Zapper
==========

[](#zip-zapper)

Validate postal/ZIP codes for any country worldwide.

[![Latest Stable Version](https://camo.githubusercontent.com/0e74091bc75ee2693304baf720c4ceb8f298f1b49123ffeafaffbea4ff4e4407/68747470733a2f2f706f7365722e707567782e6f72672f64657461696e2f7a69702d7a61707065722f76657273696f6e)](https://packagist.org/packages/detain/zip-zapper)[![Total Downloads](https://camo.githubusercontent.com/5664775731e526179b39100497927c0d3496a8f1b28dad01ba878183f5673590/68747470733a2f2f706f7365722e707567782e6f72672f64657461696e2f7a69702d7a61707065722f646f776e6c6f616473)](https://packagist.org/packages/detain/zip-zapper)[![License](https://camo.githubusercontent.com/85419a792acaa6f5770b17cd1d4969dafcbc7f0e359763f663e7c92e6c069277/68747470733a2f2f706f7365722e707567782e6f72672f64657461696e2f7a69702d7a61707065722f6c6963656e7365)](https://packagist.org/packages/detain/zip-zapper)[![Build Status](https://camo.githubusercontent.com/9c95eb09b4239a3834c65592585243869d6d556bbeb568ebc2380196a7662d66/68747470733a2f2f7472617669732d63692e6f72672f64657461696e2f7a69702d7a61707065722e7376673f6272616e63683d6d6173746572)](https://travis-ci.org/detain/zip-zapper)[![Code Climate](https://camo.githubusercontent.com/d48c724c59372d83c0067b69191e893a593a1c9a088bc906554a2ebe906ecb82/68747470733a2f2f636f6465636c696d6174652e636f6d2f6769746875622f64657461696e2f7a69702d7a61707065722f6261646765732f6770612e737667)](https://codeclimate.com/github/detain/zip-zapper)[![Scrutinizer Code Quality](https://camo.githubusercontent.com/d6ed9615ea0658aa7b5f79b42f3153215e50f3f980124650c887c14093ba1649/68747470733a2f2f7363727574696e697a65722d63692e636f6d2f672f64657461696e2f7a69702d7a61707065722f6261646765732f7175616c6974792d73636f72652e706e673f623d6d6173746572)](https://scrutinizer-ci.com/g/detain/zip-zapper/?branch=master)[![Codacy Badge](https://camo.githubusercontent.com/f822bcf4725b8dff2c106381f533096f9df24d3995de652b78b225a133567461/68747470733a2f2f6170692e636f646163792e636f6d2f70726f6a6563742f62616467652f47726164652f3635393532336636336531363438376561373166366237363339303864303965)](https://www.codacy.com/app/detain/zip-zapper)

PHP library for validating postal/ZIP codes by country. Covers **200+ countries** using format data sourced from [Wikipedia's List of Postal Codes](https://en.wikipedia.org/wiki/List_of_postal_codes).

Based on [sirprize/postal-code-validator](https://github.com/sirprize/postal-code-validator) with major expansions: 100+ new country validations, space-ignore mode, localised code names (CEP, PLZ, PIN, Eircode …), and an automated Wikipedia parser to keep formats current.

Installation
------------

[](#installation)

```
composer require detain/zip-zapper
```

Quick Start
-----------

[](#quick-start)

```
use Detain\ZipZapper\Validator;
use Detain\ZipZapper\ValidationException;

$validator = new Validator();

// Check if a country is supported
$validator->hasCountry('US'); // true
$validator->hasCountry('XX'); // false

// Validate a postal code
$validator->isValid('US', '81301');         // true
$validator->isValid('US', '8130');          // false  (too short)
$validator->isValid('GB', 'SW1A 1AA');      // true
$validator->isValid('CA', 'K1A 0B1');       // true
$validator->isValid('DE', '50672');         // true

// Validate ignoring spaces (useful for user-input normalisation)
$validator->isValid('CZ', '60200');         // false  (format requires space: '602 00')
$validator->isValid('CZ', '60200', true);   // true   (space treated as optional)

// Get the local name for the postal code concept
$validator->getZipName('US'); // 'ZIP code'
$validator->getZipName('DE'); // 'PLZ'
$validator->getZipName('IE'); // 'Eircode'
$validator->getZipName('IN'); // 'PIN code'
$validator->getZipName('BR'); // 'CEP'
$validator->getZipName('ZZ'); // 'Postal Code'  (default fallback)

// Get the descriptive expansion of the local acronym
$validator->getZipAcronym('US'); // 'Zone Improvement Plan'
$validator->getZipAcronym('DE'); // 'Postleitzahl (Postal Routing Number)'
$validator->getZipAcronym('CA'); // ''  (no acronym registered)
$validator->getZipAcronym('XX'); // ''  (unknown country)

// Get all valid format strings for a country
$validator->getFormats('US'); // ['#####', '#####-####']
$validator->getFormats('GB'); // ['@#', '@##', '@@#', '@@##', '@#@', '@@#@', '@@@', '@# #@@', ...]

// List every supported ISO 3166-1 alpha-2 country code
$validator->getCountries(); // ['AD', 'AE', 'AF', 'AG', 'AI', 'AL', ... 'ZW']
```

Handling Exceptions
-------------------

[](#handling-exceptions)

`isValid()` and `getFormats()` throw `ValidationException` for unrecognised country codes. Use `hasCountry()` first, or catch the exception:

```
use Detain\ZipZapper\Validator;
use Detain\ZipZapper\ValidationException;

$validator = new Validator();

// Safe pattern using hasCountry()
if ($validator->hasCountry($countryCode)) {
    $valid = $validator->isValid($countryCode, $postalCode);
}

// Or catch the exception
try {
    $valid = $validator->isValid($countryCode, $postalCode);
} catch (ValidationException $e) {
    echo 'Unknown country code: ' . $e->getMessage();
}
```

Format String Convention
------------------------

[](#format-string-convention)

Format strings describe the structure of a postal code:

SymbolMatchesExample`#`One digit `[0-9]``#####` → `81301``@`One letter `[a-zA-Z]``@#@ #@#` → `K1A 0B1`` `Literal space`### ##` → `113 37`A space is required unless `$ignoreSpaces = true` is passed to `isValid()`.

### Selected country formats

[](#selected-country-formats)

CountryCodeFormat(s)USA`US``#####`, `#####-####`Canada`CA``@#@ #@#`UK`GB``@# #@@`, `@## #@@`, `@@# #@@`, `@@## #@@` …Germany`DE``##`, `####`, `#####`Japan`JP``###-####`Ireland`IE``@## @#@#`, `@## @@##`, `@## @#@@` …Sweden`SE``### ##`Australia`AU``####`Brazil`BR``#####`, `#####-###`Countries Without a Postal Code System
--------------------------------------

[](#countries-without-a-postal-code-system)

About 50 countries have no postal code system (e.g. AE, AG, AO, AW, BF). Their `$formats` entry is `[]`, and `isValid()` returns `true` for any input:

```
$validator->isValid('AE', 'anything'); // true — UAE has no postal system
$validator->isValid('AE', '');         // true
$validator->getFormats('AE');          // []
```

API Reference
-------------

[](#api-reference)

### `isValid(string $countryCode, string $postalCode, bool $ignoreSpaces = false): bool`

[](#isvalidstring-countrycode-string-postalcode-bool-ignorespaces--false-bool)

Validate `$postalCode` for `$countryCode`. Returns `true` if it matches any registered format, or if the country has no postal system. Throws `ValidationException` for unrecognised country codes.

### `getFormats(string $countryCode): string[]`

[](#getformatsstring-countrycode-string)

Return the format strings for a country (`[]` for countries with no postal system). Throws `ValidationException` for unrecognised country codes.

### `hasCountry(string $countryCode): bool`

[](#hascountrystring-countrycode-bool)

Return `true` if `$countryCode` is in the registry (does not throw).

### `getZipName(string $countryCode): string`

[](#getzipnamestring-countrycode-string)

Return the local postal code name (`'ZIP code'`, `'PLZ'`, `'CEP'`, `'NPA'`, `'Eircode'`, `'PIN code'`, `'CAP'`, `'Postcode'`, `'Postal Code'`). Never throws — defaults to `'Postal Code'`.

### `getZipAcronym(string $countryCode): string`

[](#getzipacronymstring-countrycode-string)

Return the descriptive expansion for a country's postal code acronym (e.g. `'Zone Improvement Plan'` for `US`, `'Postleitzahl (Postal Routing Number)'`for `DE`). Returns `''` for countries with no published acronym and for unknown country codes. Never throws.

### `getCountries(): string[]`

[](#getcountries-string)

Return every ISO 3166-1 alpha-2 country code known to the validator, including countries with no postal code system (empty `$formats` arrays).

Country-Specific Names and Acronyms
-----------------------------------

[](#country-specific-names-and-acronyms)

The following countries have a localised name registered. All other countries fall back to `'Postal Code'` from `getZipName()` and `''`from `getZipAcronym()`.

ISONameAcronymBRCEPCódigo de endereçamento postal (Postal Addressing Code)CAPostal Code—CHNPANuméro postal d'acheminementDEPLZPostleitzahl (Postal Routing Number)IEEircode—INPIN codePostal Index NumberITCAPCodice di Avviamento Postale (Postal Expedition Code)NLPostcode—USZIP codeZone Improvement PlanAdding a New Country
--------------------

[](#adding-a-new-country)

1. Add an entry to `$formats` in `src/Validator.php`, keyed by the ISO 3166-1 alpha-2 code.
2. Use `#` for digits and `@` for letters; use `[]` for no postal system.
3. Optionally add an entry to `$zipNames` if the country uses a distinct local name.
4. Add test cases to `tests/Detain/Tests/ZipZapper/ValidatorTest.php`.

```
// In $formats:
'XX' => ['#####', '#####-####'],  // Country Name

// In $zipNames (optional):
'XX' => ['name' => 'PIN', 'acronym_text' => 'Postal Index Number'],
```

Updating Format Data from Wikipedia
-----------------------------------

[](#updating-format-data-from-wikipedia)

`bin/parse.php` fetches the Wikipedia postal codes list and prints updated PHP array lines.

> **Note:** requires the parent MyAdmin environment — cannot run standalone.

```
# From the MyAdmin root:
php vendor/detain/zip-zapper/bin/parse.php > /tmp/new_formats.php
# Review output, then paste into the $formats array in src/Validator.php
```

> **Known limitation:** Wikipedia entries that describe a single literal code (e.g. `AI-2640` for Anguilla, `BIOT 1ZZ` for British Indian Ocean Territory) contain literal letters that the parser cannot distinguish from format-symbol `A`s, so they will be mangled (e.g. `AI-2640` → `@I-2640`). Always review the generated output by hand before committing.

Development
-----------

[](#development)

```
composer install                       # install dependencies
composer test                          # run the test suite (PHPUnit)
vendor/bin/phpunit tests/ --testdox    # readable test output
```

### Requirements

[](#requirements)

- PHP **7.2+** (no runtime dependencies)
- PHPUnit **9.6+** (dev only)

Resources
---------

[](#resources)

- [List of Postal Codes](https://en.wikipedia.org/wiki/List_of_postal_codes) — Wikipedia source
- [Postal Systems by Country](https://en.wikipedia.org/wiki/Category:Postal_system)

License
-------

[](#license)

MIT — see [LICENSE](LICENSE).

###  Health Score

45

—

FairBetter than 91% of packages

Maintenance61

Regular maintenance activity

Popularity30

Limited adoption so far

Community13

Small or concentrated contributor base

Maturity61

Established project with proven stability

 Bus Factor1

Top contributor holds 92.2% of commits — single point of failure

How is this calculated?**Maintenance (25%)** — Last commit recency, latest release date, and issue-to-star ratio. Uses a 2-year decay window.

**Popularity (30%)** — Total and monthly downloads, GitHub stars, and forks. Logarithmic scaling prevents top-heavy scores.

**Community (15%)** — Contributors, dependents, forks, watchers, and maintainers. Measures real ecosystem engagement.

**Maturity (30%)** — Project age, version count, PHP version support, and release stability.

###  Release Activity

Cadence

Every ~427 days

Total

3

Last Release

2537d ago

Major Versions

v1.0.1 → v2.0.02019-07-23

PHP version history (2 changes)v1.0.0PHP &gt;=5.3.2

v2.0.0PHP &gt;=5.4

### Community

Maintainers

![](https://www.gravatar.com/avatar/b1036e0717211b8030b83cbe729e8ba6ba442fdbd5285fb97a39d7dcfe339342?d=identicon)[detain](/maintainers/detain)

---

Top Contributors

[![detain](https://avatars.githubusercontent.com/u/1364504?v=4)](https://github.com/detain "detain (142 commits)")[![kumar-interserver](https://avatars.githubusercontent.com/u/29834101?v=4)](https://github.com/kumar-interserver "kumar-interserver (10 commits)")[![mend-bolt-for-github[bot]](https://avatars.githubusercontent.com/in/16809?v=4)](https://github.com/mend-bolt-for-github[bot] "mend-bolt-for-github[bot] (1 commits)")[![peter279k](https://avatars.githubusercontent.com/u/9021747?v=4)](https://github.com/peter279k "peter279k (1 commits)")

---

Tags

addressaddress-validationapicepeircodeiso-3166librarynpaphpphp-librarypin-codeplzpostal-codepostal-codesrestrest-apivalidationvalidatorzip-codevalidatorzipzip codecepzipcodepostcodepostal-codeplzcapeircodenpapin codepostal expedition codepostal addressing coddenumro postal dacheminementpostal index numberPostal Routing Numberzone improvement plan

###  Code Quality

TestsPHPUnit

### Embed Badge

![Health badge](/badges/detain-zip-zapper/health.svg)

```
[![Health](https://phpackages.com/badges/detain-zip-zapper/health.svg)](https://phpackages.com/packages/detain-zip-zapper)
```

###  Alternatives

[barbieswimcrew/zip-code-validator

Constraint class for international zipcode validation

772.5M](/packages/barbieswimcrew-zip-code-validator)[sirprize/postal-code-validator

Validate Formatting Of World-Wide Postal Codes

782.0M1](/packages/sirprize-postal-code-validator)[canducci/zipcode

ZipCode From Brazil

4555.8k](/packages/canducci-zipcode)

PHPackages © 2026

[Directory](/)[Categories](/categories)[Trending](/trending)[Changelog](/changelog)[Analyze](/analyze)
