search
HomeBackend DevelopmentPHP TutorialHow to verify ID card format using PHP regular expression

How to verify ID card format using PHP regular expression

Jun 24, 2023 am 10:34 AM
phpregular expressionID card

ID card is an important document. For websites, apps and other applications, it is often necessary to verify whether the ID number entered by the user meets the specifications. PHP provides a very convenient way to achieve this function, that is, using regular expressions.

This article will introduce how to use PHP regular expressions to verify the correct format of the ID number.

1. ID card number format

Before using PHP regular expressions to verify the ID card number format, we first need to understand the format regulations of the ID card number. China's ID card number format has a total of 18 digits, the first 17 digits are numbers, and the last digit is a check code (which may be numbers or capital letters).

The specific provisions are as follows:

  1. The first 6 digits are the address code, indicating the administrative division code of the place of household registration.
  2. Next is the 8-digit date of birth in the format YYYYMMDD.
  3. The next 4 digits are the sequence code, indicating the sequence number of births in the same address code area, and the last digit is the gender identifier. Odd numbers are male, even numbers are female.
  4. The last digit is the check code, which can be a number or the letter X.

Now that we know the format of the ID number, we can use PHP regular expressions to verify its correctness.

2. Regular expression verification

The preg_match function is usually used to verify regular expressions. The syntax is as follows:

preg_match($pattern, $subject);

Among them, $pattern represents the regular expression and $subject represents the need Verification string. If the match is successful, return 1, otherwise return 0.

Next, we need to build a regular expression that can verify the format of the ID number. The specific implementation method is as follows:

  1. First, use d to match numbers, and use [xXd] to match X or x or numbers.
  2. Then, use {18} to indicate repeating 18 times.
  3. Next, add interval restrictions to the first 6 digits and use the regular expression /^([1-9]d{5})/, indicating that the first digit is 1-9 and the following 5 digits is any number.
  4. Add interval restrictions to the 8-digit date of birth, using the regular expression /(d{4})([0-9]{2})([0-9]{2})/ , indicating that the first 4 digits are any numbers, the last 2 digits range from 00 to 99, and the last 2 digits are also from 00 to 99.
  5. Use the regular expression /(d{3})(d{3})(d{2})(d[xXd])/ on the sequence code, indicating that the first three digits are any numbers. The middle 3 digits are any numbers, the last 2 digits are also any numbers, and the last digit can be a number or the letter X.

To sum up, the final regular expression can be obtained:

/^([1-9]d{5})(d{4})([0-9]{2})([0-9]{2})(d{3})(d{3})(d{2})(d[xXd])$/

Using PHP regular expressions to verify the ID number requires the preg_match function. The code example is as follows:

function check_id_card($id_card) {
    // 加上正则表达式
    $reg = '/^([1-9]d{5})(d{4})([0-9]{2})([0-9]{2})(d{3})(d{3})(d{2})([dxX])$/';
    if (preg_match($reg, $id_card, $matches)) {
        // 校验地址码
        if (!check_address_code($matches[1])) {
            return false;
        }
        // 校验出生日期
        if (!check_birthday($matches[2] . "-" . $matches[3] . "-" . $matches[4])) {
            return false;
        }
        // 校验顺序码
        if (!check_order_code($matches[5])) {
            return false;
        }
        // 校验校验码
        if (!check_verify_code($matches[0])) {
            return false;
        }
        return true;
    }
    return false;
}

Among them, check_address_code, check_birthday, check_order_code, check_verify_code and other functions are used to verify the correctness of the address code, date of birth, sequence code and check code respectively, and need to be implemented according to the specific situation.

3. Summary

Through the above method, you can use PHP regular expressions to verify the correctness of the ID number. It should be noted that the verification of the ID number is not only a matter of format, but also needs to consider whether the address code is legal, whether the date of birth is within a reasonable range, whether the gender identifier of the sequence code complies with regulations, etc. Therefore, code implementation needs to take into account Many factors ensure the accuracy and reliability of verification results.

The above is the detailed content of How to verify ID card format using PHP regular expression. For more information, please follow other related articles on the PHP Chinese website!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
How can you check if a PHP session has already started?How can you check if a PHP session has already started?Apr 30, 2025 am 12:20 AM

In PHP, you can use session_status() or session_id() to check whether the session has started. 1) Use the session_status() function. If PHP_SESSION_ACTIVE is returned, the session has been started. 2) Use the session_id() function, if a non-empty string is returned, the session has been started. Both methods can effectively check the session state, and choosing which method to use depends on the PHP version and personal preferences.

Describe a scenario where using sessions is essential in a web application.Describe a scenario where using sessions is essential in a web application.Apr 30, 2025 am 12:16 AM

Sessionsarevitalinwebapplications,especiallyfore-commerceplatforms.Theymaintainuserdataacrossrequests,crucialforshoppingcarts,authentication,andpersonalization.InFlask,sessionscanbeimplementedusingsimplecodetomanageuserloginsanddatapersistence.

How can you manage concurrent session access in PHP?How can you manage concurrent session access in PHP?Apr 30, 2025 am 12:11 AM

Managing concurrent session access in PHP can be done by the following methods: 1. Use the database to store session data, 2. Use Redis or Memcached, 3. Implement a session locking strategy. These methods help ensure data consistency and improve concurrency performance.

What are the limitations of using PHP sessions?What are the limitations of using PHP sessions?Apr 30, 2025 am 12:04 AM

PHPsessionshaveseverallimitations:1)Storageconstraintscanleadtoperformanceissues;2)Securityvulnerabilitieslikesessionfixationattacksexist;3)Scalabilityischallengingduetoserver-specificstorage;4)Sessionexpirationmanagementcanbeproblematic;5)Datapersis

Explain how load balancing affects session management and how to address it.Explain how load balancing affects session management and how to address it.Apr 29, 2025 am 12:42 AM

Load balancing affects session management, but can be resolved with session replication, session stickiness, and centralized session storage. 1. Session Replication Copy session data between servers. 2. Session stickiness directs user requests to the same server. 3. Centralized session storage uses independent servers such as Redis to store session data to ensure data sharing.

Explain the concept of session locking.Explain the concept of session locking.Apr 29, 2025 am 12:39 AM

Sessionlockingisatechniqueusedtoensureauser'ssessionremainsexclusivetooneuseratatime.Itiscrucialforpreventingdatacorruptionandsecuritybreachesinmulti-userapplications.Sessionlockingisimplementedusingserver-sidelockingmechanisms,suchasReentrantLockinJ

Are there any alternatives to PHP sessions?Are there any alternatives to PHP sessions?Apr 29, 2025 am 12:36 AM

Alternatives to PHP sessions include Cookies, Token-based Authentication, Database-based Sessions, and Redis/Memcached. 1.Cookies manage sessions by storing data on the client, which is simple but low in security. 2.Token-based Authentication uses tokens to verify users, which is highly secure but requires additional logic. 3.Database-basedSessions stores data in the database, which has good scalability but may affect performance. 4. Redis/Memcached uses distributed cache to improve performance and scalability, but requires additional matching

Define the term 'session hijacking' in the context of PHP.Define the term 'session hijacking' in the context of PHP.Apr 29, 2025 am 12:33 AM

Sessionhijacking refers to an attacker impersonating a user by obtaining the user's sessionID. Prevention methods include: 1) encrypting communication using HTTPS; 2) verifying the source of the sessionID; 3) using a secure sessionID generation algorithm; 4) regularly updating the sessionID.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Atom editor mac version download

Atom editor mac version download

The most popular open source editor

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor