Home > Article > Backend Development > How to use regular expressions in php to match only ID cards
Regular expression is a tool commonly used in programs. It can use a series of rules to match and modify text. In PHP, the use of regular expressions is very important, mainly used for string matching, replacement and extraction operations.
Among all regular expressions, matching ID number is a classic problem. In PHP, we can match ID numbers through a series of regular expressions.
First of all, we need to understand the structure of the ID number. According to the national standard "Citizen Identity Number" (GB 11643-1999), the ID number has 18 digits in total. The first 17 digits are the area code and date of birth code, and the 18th digit is the check code.
Among them, the first 6 digits are the region code, including the abbreviations of provinces, autonomous regions, and municipalities directly under the Central Government. The 7th to 14th digits are the date, month and day of birth code in the format of YYYYMMDD. The 15th to 17th digits are the serial numbers, that is, the serial numbers of people born on the same day in the same area. An odd number in the 17th digit indicates a male, and an even number indicates a female. The last digit is a check code, which is a number calculated according to national standards.
According to the structure of the ID number, we can write the following PHP regular expression:
$pattern = '/^([1-9]\d{5})(19\d{2}|20\d{2})(0[1-9]|1[012])(0[1-9]|[12]\d|3[01])\d{3}(\d|X)$/i';
In the above regular expression:
The match of the last check code is special. Because it may end up being X, we use (\d|X) to represent it.
Use the preg_match function to match the ID number. The code is as follows:
$pattern = '/^([1-9]\d{5})(19\d{2}|20\d{2})(0[1-9]|1[012])(0[1-9]|[12]\d|3[01])\d{3}(\d|X)$/i'; $id_card = '11010119880101001X'; if (preg_match($pattern, $id_card)) { echo '匹配成功'; } else { echo '匹配失败'; }
In this example, the two variables $pattern and $id_card are passed as parameters to the preg_match function. If the match is successful, "match successful" will be output, otherwise "match failed" will be output.
In short, PHP regular expression is a very powerful tool that can be used to match complex strings such as ID numbers. Through this article, you should master how to use regular expressions to match ID numbers in PHP.
The above is the detailed content of How to use regular expressions in php to match only ID cards. For more information, please follow other related articles on the PHP Chinese website!