**
身份证号码验证规则思路:
- 判断身份证号码位数
- 身份证区域码验证
- 统一验证位数(18位)
- 18位身份证号码合法性验证
**
代码展示:
public function validation_filter_id_card($id_card){
global $_GPC,$_W;
if(empty($id_card)){
return false;
}
$City = array(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=>"国外");
$iSum = 0;
$idCardLength = strlen($id_card);
//长度验证
if(!preg_match('/^\d{17}(\d|x)$/i',$id_card) and!preg_match('/^\d{15}$/i',$id_card)){
return "请输入正确的省份证号码---身份证号位数不正确";
}
//地区验证
if(!array_key_exists(intval(substr($id_card,0,2)),$City)){
return "请输入正确的省份证号码---身份证的地区号不正确";
}
// var_dump($idCardLength);die;
//15位身份证验证生日,转换为18位
if($idCardLength == 15){
$sBirthday = '19'.substr($id_card,6,2).'-'.substr($id_card,8,2).'-'.substr($id_card,10,2);
$d = new DateTime($sBirthday);
$dd = $d->format('Y-m-d');
if($sBirthday != $dd){
return false;
}
$id_card = substr($id_card,0,6)."19".substr($id_card,6,9);//15to18
$Bit18 = $this->getVerifBit($id_card);//算出第18位校验码
$id_card = $id_card.$Bit18;
// var_dump($id_card);die;
}
//判断是否大于2078年,小于1900年
$year = substr($id_card,6,4);
if($year<1900 || $year>2078){
return false;
}
//18位身份证处理
$sBirthday = substr($id_card,6,4).'-'.substr($id_card,10,2).'-'.substr($id_card,12,2);
$d = new DateTime($sBirthday);
$dd = $d->format($sBirthday);
if($sBirthday != $dd){
return false;
}
//身份证编码规范验证
$idcard_base = substr($id_card,0,17);
if(strtoupper(substr($id_card,17,1)) != $this->getVerifBit($idcard_base)){
// var_dump('省份证号码错误');die;
return false;
}
return $id_card;
}
//计算身份证校验码,根据国家标准GB 11643-1999
public function getVerifBit($idcard_base){
if(strlen($idcard_base) != 17){
return false;
}
//加权因子
$factor = array(7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2);
//校验码对应值
$verify_number_list = array('1', '0', 'X', '9', '8', '7', '6', '5', '4','3', '2');
$checksum = 0;
for($i=0;$i<strlen($idcard_base);$i++){
$checksum += substr($idcard_base, $i, 1) * $factor[$i];
}
$mod = $checksum % 11;
$verify_number = $verify_number_list[$mod];
return $verify_number;
}
总结
每天学习一点点