-
-
Save j-mccarthy/2a13675cdb3d0506d475d3a8de560948 to your computer and use it in GitHub Desktop.
Simple regex for Canadian postal codes in PHP
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment