Postal code is a very commonly used address identifier, which can clearly locate the location of an address and allow us to find the target location quickly and accurately. In web pages, we often need to verify whether the zip code format is correct to ensure that users enter correct address information. Below we will introduce how to use PHP regular expressions to verify the zip code format.
In PHP, use the preg_match() function to match regular expressions. We can enter a regular expression and a string to be matched to determine whether the string matches the regular expression. The specific format is as follows:
preg_match(string $pattern, string $subject, [array &$matches])
where $pattern is a regular expression and $subject is the string to be matched. $matches is an optional output variable used to store matched substrings. If the return value is 1, the match is successful. Here is a simple example:
$subject = "hello world";
$pattern = "/world/";
$result = preg_match($pattern, $subject);
if ($result == 1) {
echo "匹配成功";
} else {
echo "匹配失败";
}
The above code will output "match successfully" because the string "world " was found in $subject.
So, how to use regular expressions to determine whether the zip code format is correct? In China, the postal code consists of 6 numbers. We can use d to represent a numeric character and {} to limit the number of times this character appears. That is to say, the regular expression for zip code should be as follows:
$pattern = "/^d{6}$/";
This regular expression means: start with a It starts with a numeric character, then 6 numeric characters appear, followed by the end of the string. This meets the requirements of China's postal code, so only 6 numbers can be entered to successfully match.
The following is a complete PHP code example. You can enter the zip code into the web page to verify whether the format is correct:
< ;head>
<meta charset="UTF-8"> <title>邮编格式验证</title>
<form method="post"> 请输入邮编:<input type="text" name="zip_code"><br> <input type="submit" value="验证"> </form> <?php if ($_SERVER["REQUEST_METHOD"] == "POST") { $zip_code = $_POST["zip_code"]; $pattern = "/^d{6}$/"; if (preg_match($pattern, $zip_code)) { echo "<p style='color:green'>邮编格式正确</p>"; } else { echo "<p style='color:red'>邮编格式错误</p>"; } } ?>