I need to check the zip code in the specific format that was provided to me for each country.
For instance:
$postcode_validation = array ( 'Australia' => array('NNNN'), 'Bahrain' => array('NNN', 'NNNN'), 'Netherlands' => array('NNNN AA'), 'United States' => array('NNNNN', 'NNNNN-NNNN', 'NNNNN-NNNNNN') );
Each country can have as many zip code format options as they want; Where:
- N = number [0-9]
- A = Letters [a-zA-Z]
- and it sometimes allows / contains gypsum
So, if we take Australia for example, it should confirm true for:
etc...
and should fail on:
etc...
Given this, I am trying to create the only function that I can use to check the zip code for a given country for all zip code options. the function should return true if the zip code matches at least one rule, and return false if no match is found.
So here is how I tried to do this (starting with a simple one):
<?php // mapping $postcode_validation = array ( 'Australia' => array('NNNN'), 'Bahrain' => array('NNN', 'NNNN'), 'Netherlands' => array('NNNN AA'), 'United States' => array('NNNNN', 'NNNNN-NNNN', 'NNNNN-NNNNNN') ); // helper function function isPostcodeValid($country, $postcode) { // Load Mapping global $postcode_validation; // Init $is_valid = false; // Check If Country Exists if (!array_key_exists($country, $postcode_validation)) return false; // Load Postcode Validation Rules $validation_rules = $postcode_validation[$country]; // Iterate Through Rules And Check foreach ($validation_rules as $validation_rule) { // Replace N with \d for regex $validation_rule = str_replace('N', '\\d', $validation_rule); // Check If Postcode Matches Pattern if (preg_match("/$validation_rule/", $postcode)) { $is_valid = true; break; } } // Finished return $is_valid; } // Test $myCountry = 'Australia'; $myPostcode = '1468'; var_dump(isPostcodeValid($myCountry, $myPostcode)); ?>
It seems to work, returning the truth. But it also returns true for $myPostcode = '1468a';
Does anyone have a way to do this dynamic zip code check by fixed rules?
Refresh
This is how it was decided; using regex from the Zend library: http://pastebin.com/DBKhpkur