[PHP] Check zip code with regular expression

Sep 9, 2020 PHP formal performance beginners post number

This time we will use the code below.
$ zip = '123-4567'; // ← full-width

$ zip = mb_convert_kana ($ zip,'a','UTF-8');
if (preg_match ("/ \ A \ d {3} [-] \ d {4} \ z /", $ zip)) {
  print ('Zip code: 〒'. $ Zip);
} else {
  print ('* Please enter the zip code in the format 123-4567');
}

It is displayed as ↓.

Zip code: 〒123-4567 // ← Half-width
Reason for specifying “**‘a’ **” in the parameter

Since the zip code is a number, what about “**‘n’ **”? You might think, Since -(hyphen) ** is included, it is treated as alphanumeric characters. By specifying “‘a’ **”, you can convert alphanumeric characters to half-width characters.

As for the regular expression of the main subject, first we use the function preg_match. Let’s take a look at the following / \ A \ d {3} [-] \ d {4} \ z /.


\ d {3}

** d ** is the number “DECIMAL” ** {3} ** is 3 In other words, the specification ** “arrange three numbers” **

[-]

Specify that the front and back should be connected with **-(hyphen) **

\ d {4}

** “Arrange 4 numbers” **

So far, we have checked the zip code format with \ d {3} [-] \ d {4}.

Then, what are the “** \ A **” and “** \ z **” before and after?

\ A

** Specify “Be the beginning of the sentence” **

\ z

** Specify “at the end of the sentence” **

In summary, / \ A \ d {3} [-] \ d {4} \ z / is “Three numbers are lined up at the beginning, with a- (hyphen) in between, and four numbers are lined up at the end.” It will be the description of the rule.

**-(Hyphen) ** The presence or absence is also checked, so $ zip = '1234567';

* Please enter the postal code in the format 123-4567.

Is returned.


that’s all. Thank you for your hard work.