REGEXVAULTv2.0
Localization/Postal Codes
Verified Safe

Canadian Postal Code Regex for PHP

/^([ABCEGHJKLMNPRSTVXY][0-9][ABCEGHJKLMNPRSTVWXYZ])\s?([0-9][ABCEGHJKLMNPRSTVWXYZ][0-9])$/i

What this pattern does

This page provides a comprehensive, battle-tested regular expression for matching canadian postal code, ported and verified for PHP. A rigorously tested regex reduces debugging time and protects your application from edge-case failures. The snippet below is ready to drop into your PHP project — whether you're validating in a Laravel validator, a WordPress plugin, or a standalone PHP script.

Php Implementation

Php
<?php
// Canadian Postal Code
// ReDoS-safe | RegexVault — Localization > Postal Codes

define('CANADIAN_POSTAL_CODE_PATTERN', '/^([ABCEGHJKLMNPRSTVXY][0-9][ABCEGHJKLMNPRSTVWXYZ])\s?([0-9][ABCEGHJKLMNPRSTVWXYZ][0-9])$/');

function validate_canadian_postal_code(string $input): bool {
    return (bool) preg_match(CANADIAN_POSTAL_CODE_PATTERN, $input);
}

// Example
var_dump(validate_canadian_postal_code("K1A 0B1")); // bool(true)

Test Cases

Matches (Valid)
Rejects (Invalid)
K1A 0B1K1A 0B
M5V 3L9K1A0B12
V6B 1G4Z1A 0B1
T2P 3C3K1A OB1
K1A0B1D1A 0B1

When to use this pattern

This pattern is drawn from the Localization > Postal Codes category and carries a ReDoS-safe certification. That matters for PHP developers because especially relevant in PHP where PCRE backtracking limits can trigger silent failures on malicious input. RegexVault audits patterns against known backtracking attack vectors, ensuring you have the necessary context before using this regex in a high-stakes production environment.

Common Pitfalls

The FSA (Forward Sortation Area, first 3 characters) uniquely identifies a delivery area. The LDU (Local Delivery Unit, last 3) narrows to a block. The boundary between FSA and LDU is always a space.

Technical Notes

First letter identifies the province. Invalid first letters: D, F, I, O, Q, U, W (excluded because they resemble digits in some fonts or were reserved). The letter D and I are also excluded from all positions for readability.

Have a pattern that belongs in the vault?

Submit it for review — community-verified patterns get credited to your GitHub handle. Free submissions join the queue. Priority review available for $15.

Submit a Pattern