Checking dynamic zip code

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:

  • 1245
  • 4791
  • 7415

etc...

and should fail on:

  • a113
  • 18q5
  • 1s-s7

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

+8
source share
2 answers

Check the following validator from ZF2:

Validator / PostCode.php

It has all the regular expressions you need. Just add start and end anchors. See Line 358.

+2
source

OP regex did not work correctly because it did not take into account the beginning and end of the line.

As @ cOle2 commented, line

 if (preg_match("/$validation_rule/", $postcode)) { 

should be changed to

 if (preg_match("/^$validation_rule$/", $postcode)) { 

Also, as noted in the OP editing, another good solution is to use a regular expression from the Zend library: http://pastebin.com/DBKhpkur

0
source

Source: https://habr.com/ru/post/972398/


All Articles