1/** 2 * 校验身份证号码是否合法 3 * @param $str 4 * @param bool $getBasicInfo 是否提取身份证号码中的基本信息(出生日期/性别) 5 * @return mixed 6 */ 7 public static function RegexpMatchIdCard($str, $getBasicInfo = false) 8 { 9 //校验身份证位数和出生日期部分 10 $pattern = "/^\d{6}(18|19|20)?\d{2}(0[1-9]|1[012])(0[1-9]|[12]\d|3[01])\d{3}(\d|[xX])$/"; 11 preg_match($pattern, $str, $match); 12 $result = $match ? true : false; 13 if (!$result) { 14 return false; 15 } 16 17 //校验前两位是否是所有省份代码 18 $province_code = ['11', '12', '13', '14', '15', '21', '22', '23', '31', '32', '33', '34', '35', '36', '37', '41', '42', '43', '44', '45', '46', '50', '51', '52', '53', '54', '61', '62', '63', '64', '65', '71', '81', '82', '91']; 19 if (!in_array(substr($str, 0, 2), $province_code)) { 20 return false; 21 } 22 23 //校验身份证最后一位 24 $ahead17_char = substr($str, 0, 17); 25 $last_char = substr($str, -1); 26 $factor = array(7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2); // 前17位的权重 27 $c = array(1, 0, 'X', 9, 8, 7, 6, 5, 4, 3, 2); //模11后的对应校验码 28 $t_res = 0; 29 for ($i = 0; $i < 17; $i++) { 30 $t_res += intval($ahead17_char[$i]) * $factor[$i]; 31 } 32 $calc_last_char = $c [$t_res % 11]; 33 if ($last_char != $calc_last_char) { 34 return false; 35 } 36 37 if (!$getBasicInfo) { 38 return $result; 39 } 40 41 //从身份证号码中提取出生日期和性别 42 $birth_year = substr($str, 6, 4); 43 $birth_month = substr($str, 10, 2); 44 $birth_day = substr($str, 12, 2); 45 if (!checkdate($birth_month, $birth_day, $birth_year)) { 46 return false; 47 } 48 $brithday = $birth_year . "-" . $birth_month . "-" . $birth_day; 49 $gender_char = substr($str, -2, 1); 50 if ($gender_char % 2 == 0) { 51 $gender = 2; //女 52 } else { 53 $gender = 1; //男 54 } 55 56 return [ 57 'birthday' => $brithday, 58 'age' => self::getAge(strtotime($brithday)), 59 'gender' => $gender, 60 ]; 61 } 62 63 /** 64 * 根据出生日期获取年龄 65 * @param string $birthday 出生日期时间戳 66 * @return false|string 67 */ 68 public static function getAge($birthday) 69 { 70 //格式化出生时间年月日 71 $byear = date('Y', $birthday); 72 $bmonth = date('m', $birthday); 73 $bday = date('d', $birthday); 74 75 //格式化当前时间年月日 76 $tyear = date('Y'); 77 $tmonth = date('m'); 78 $tday = date('d'); 79 80 //计算年龄 81 $age = $tyear - $byear; 82 if ($bmonth > $tmonth || $bmonth == $tmonth && $bday > $tday) { 83 $age--; 84 } 85 return $age; 86 }
PHP校验身份证号码是否合法
Wesley13
2021-10-11
1135 0 0
点赞
收藏
评论区
加载中...