1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143
| 下面是身份证编码各个部分的含义:
class IdentityCard {
public static function isValid(string $num){ $length = strlen($num); if ($length == 15) {
if (!is_numeric($num)) { return false; } $areaNum = substr($num, 0, 6); $dateNum = substr($num, 6, 6);
} else if ($length == 18) {
if (!preg_match('/^\d{17}[0-9xX]$/', $num)) { return false; } $areaNum = substr($num, 0, 6); $dateNum = substr($num, 6, 8);
} else { return false; }
if (!self::isAreaCodeValid($areaNum)) { return false; }
if (!self::isDateValid($dateNum)) { return false; }
if (!self::isVerifyCodeValid($num)) { return false; }
return true; }
private static function isAreaCodeValid(string $area) { $provinceCode = substr($area, 0, 2);
if (11 <= $provinceCode && $provinceCode <= 65) { return true; } else { return false; } }
private static function isDateValid(string $date) { if (strlen($date) == 6) { $date = '19'.$date; } $year = intval(substr($date, 0, 4)); $month = intval(substr($date, 4, 2)); $day = intval(substr($date, 6, 2));
if (!checkdate($month, $day, $year)) { return false; }
$currYear = date('Y'); if ($year > $currYear) { return false; } return true; }
private static function isVerifyCodeValid(string $num){ if (strlen($num) == 18) { $factor = [7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2]; $tokens = ['1', '0', 'X', '9', '8', '7', '6', '5', '4', '3', '2'];
$checkSum = 0; for ($i = 0; $i < 17; $i++) { $checkSum += intval($num{$i}) * $factor[$i]; }
$mod = $checkSum % 11; $token = $tokens[$mod];
$lastChar = strtoupper($num{17});
if ($lastChar != $token) { return false; } } return true; } }
|