PHP function to verify ID number and extract age

要实现一个 PHP 函数来验证身份证号码并提取年龄,可以使用以下代码:

/**
 * 验证身份证号码并提取年龄
 * @param $id
 * @return false|int|string
 */
function isIdno($id){
    
    
    $id = strtoupper($id);
    $regx = "/(^\d{15}$)|(^\d{17}([0-9]|X)$)/";
    $arr_split = array();
    if(!preg_match($regx, $id)){
    
    
        return false;
    }
    if(15==strlen($id)){
    
    //检查15位
        $regx = "/^(\d{6})+(\d{2})+(\d{2})+(\d{2})+(\d{3})$/";
        @preg_match($regx, $id, $arr_split);
        //检查生日日期是否正确
        $dtm_birth = "19".$arr_split[2] . '/' . $arr_split[3]. '/' .$arr_split[4];
        if(!strtotime($dtm_birth)) {
    
    
            return false;
        }else{
    
    
            //提取年龄
            $age = date("Y") - (int)substr($id, 6, 2);
            return $age;
        }
    }else{
    
    //检查18位
        $regx = "/^(\d{6})+(\d{4})+(\d{2})+(\d{2})+(\d{3})([0-9]|X)$/";
        @preg_match($regx, $id, $arr_split);
        $dtm_birth = $arr_split[2] . '/' . $arr_split[3]. '/' .$arr_split[4];

        if(!strtotime($dtm_birth)){
    
    //检查生日日期是否正确
            return false;
        }else{
    
    
            //提取年龄
            $age = date("Y") - (int)substr($id, 6, 4);
            return $age;
        }
    }
}

The main implementation principle is: first convert the ID number to uppercase, and then use regular expressions to check whether its format is correct. If the format is correct, the function will check whether the date of birth is correct, and then perform different processing based on the length of the ID number. If the date of birth is correct, the function will extract and return the age. If the date of birth is incorrect, the function will return false.

Guess you like

Origin blog.csdn.net/u012134073/article/details/135202679