When writing a PHP application, it is sometimes necessary to perform format verification on the input ID number to ensure that the data entered by the user conforms to the standard ID card format. Regular expressions can be used in PHP to verify the ID card number format. This article will introduce how to use regular expressions to achieve this function.
First of all, we need to understand the format of the ID number. According to Chinese law, the ID number has 18 digits in total, of which the first 17 digits are numbers, and the last digit can be a number or the letter X, which is used to verify whether the ID number is entered correctly. The format of the ID number is as follows:
According to the above provisions, we can write a regular expression to match the format of the ID number. The syntax of the regular expression is as follows:
/^d{2}(0[1-9]|[1-9]d)d{2}d{4}d{2}d{2}(d{3}|d{4}[Xx])$/
where:
^
represents the starting position of the matched input string; d
means matching any number, equivalent to [0-9]
; {n}
means matching n times; ()
means grouping to facilitate subsequent operations; |
means or, used to match multiple options; $
Indicates matching the end position of the input string; []
indicates matching any character in the set. According to the above regular expression, we can pass it as a parameter to the PHP built-in function preg_match()
to verify the ID number format. preg_match()
The syntax of the function is as follows:
preg_match(string $pattern, string $subject, array &$matches = null, int $flags = 0, int $offset = 0): int|false
This function accepts a regular expression and a string to be matched as parameters. Returns 1 if there is a successful match, 0 otherwise. If an error occurs in the function, false is returned.
The following is an example of a PHP function that verifies the ID card number format:
function validate_id_card(string $id_card): bool { $pattern = '/^d{2}(0[1-9]|[1-9]d)d{2}d{4}d{2}d{2}(d{3}|d{4}[Xx])$/'; return preg_match($pattern, $id_card) === 1; }
This function accepts a string parameter id_card
, which is used to verify the ID card number format. The $pattern
variable is used inside the function to save the previously defined regular expression and is passed as a parameter to the preg_match()
function. If the function successfully matches, it returns true, otherwise it returns false.
The above is how to use regular expressions in PHP to verify the format of the ID number. Using regular expressions can complete ID card number format verification more efficiently and conveniently, avoiding the need to manually write complex verification logic.
The above is the detailed content of How to use regular expressions in PHP to verify ID number format. For more information, please follow other related articles on the PHP Chinese website!