PHP检查邮政编码

I need to verify the postal code inserted in a text box and stored in a variable: "$code".

iIf the format is like this: XXXX – XXX it's valid. If not, it's invalid (the X's are numbers).

Someone told me to make a regex like this one but applied to my needs:

$regex = "/^[ABCEGHJKLMNPRSTVXY]{1}\d{1}[A-Z]{1} *\d{1}[A-Z]{1}\d{1}$/";

Not only do I not know how to make that, but I also don't know what to do after.

Do you guys have any idea on how to solve my problem?

You could try something like :

/^[0-9]{4}\s-\s[0-9]{3}$/

Or :

/^\d{4}\s-\s\d{3}$/

EDIT : If you have 0 or more space between the - and the digits :

/^\d{4}\s*-\s*\d{3}$/

If you have 0 or only one space between the - and the digits :

/^\d{4}\s?-\s?\d{3}$/

If you haven't any spaces between the - and the digits :

/^\d{4}-\d{3}$/

Well, some more insight into the postal codes you'd like to validate would help. But here is some general advise.

Regular expressions are extremely powerful but also complicated, hard to maintain and slow compared to many other language features.

If you need to validate the length of a number, simply cast it to a string and calculate the length.

<?php

$len = strlen((string) $number);
if ($len < 3 || $len > 4) {
    // invalid
}

If you need to validate a number, use PHP's built-in filter functions.

<?php

$valid = filter_var(FILTER_VALIDATE_INT, array(
  "options" => array(
    "max" => 9999,
    "min" => 100,
  ),
));

A regular expression might come in handy if you need the separator character.

<?php

$valid = (boolean) preg_match("/^\d{4}\s(-|–|—)\s\d{3}$/");

Or combine regular expression with filter functions.

<?php

$valid = filter_input(INPUT_POST, "postalcode", FILTER_VALIDATE_REGEXP, array(
  "options" => array(
    "regexp" => "/^\d{4}\s(-|–|—)\s\d{3}$/",
  ),
));

Although you could validate it with pure PHP as well, just in case the regular expression thingy is still to complicated for you.

There are many great websites out there to learn regular expressions or to test them. A personal favorite (not affiliated with) of mine is regex101.