Skip to content

Instantly share code, notes, and snippets.

@james2doyle
Created December 2, 2014 21:36
Show Gist options
  • Save james2doyle/c310e6ceeb3bad437621 to your computer and use it in GitHub Desktop.
Save james2doyle/c310e6ceeb3bad437621 to your computer and use it in GitHub Desktop.
Simple regex for Canadian postal codes in PHP
<?php
// test with: `php valid-canadian-postal-code.php`
$expression = '/^([a-zA-Z]\d[a-zA-Z])\ {0,1}(\d[a-zA-Z]\d)$/';
// lower, no space
$valid = (bool)preg_match($expression, 'k0a3m0');
var_dump($valid);
// lower, with space
$valid2 = (bool)preg_match($expression, 'k0a 3m0');
var_dump($valid2);
// mixed case, with space
$valid3 = (bool)preg_match($expression, 'K0a 3M0');
var_dump($valid3);
// all upper case, with space
$valid4 = (bool)preg_match($expression, 'K0A 3M0');
var_dump($valid4);
// all upper case, with no space
$valid5 = (bool)preg_match($expression, 'K0A3M0');
var_dump($valid5);
// all upper case, with too many spaces
$invalid = (bool)preg_match($expression, 'K0A 3M0');
var_dump($invalid);
// with leading digit
$invalid2 = (bool)preg_match($expression, '00A 3M0');
var_dump($invalid2);
@lordspace
Copy link

why don't you just make the spaces just one?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment