$currentYearLastTwo) { $year += 1900; } else { $year += 2000; } } else { return null; } // 验证日期是否有效 if (!checkdate($month, $day, $year)) { return null; } try { return new \DateTimeImmutable(sprintf('%04d-%02d-%02d', $year, $month, $day)); } catch (\Throwable $e) { return null; } } /** * 从身份证号中提取性别 * * @param string $idCard 身份证号(15位或18位) * @return int 性别:1=男,2=女,0=未知 */ public static function extractGender(string $idCard): int { $idCard = trim($idCard); $length = strlen($idCard); if ($length === 18) { // 18位身份证:第17位(索引16)是性别码 $genderCode = (int)substr($idCard, 16, 1); } elseif ($length === 15) { // 15位身份证:第15位(索引14)是性别码 $genderCode = (int)substr($idCard, 14, 1); } else { return 0; // 未知 } // 奇数表示男性,偶数表示女性 return ($genderCode % 2 === 1) ? 1 : 2; } /** * 从身份证号中提取所有可解析的信息 * * @param string $idCard 身份证号 * @return array 包含 birthday 和 gender 的数组 */ public static function extractInfo(string $idCard): array { return [ 'birthday' => self::extractBirthday($idCard), 'gender' => self::extractGender($idCard), ]; } }