Home  >  Article  >  php教程  >  身份证号码校验

身份证号码校验

PHP中文网
PHP中文网Original
2016-05-23 08:39:151430browse

身份证号码校验

function idcard_check($id)
{
    if ( ! preg_match('/^\d{18}$|^\d{17}X$/', $id) ) {
        return false;
    }

    $id = str_split($id);
    $x  = array(7,9,10,5,8,4,2,1,6,3,7,9,10,5,8,4,2);
    $y  = array(1,0,'X',9,8,7,6,5,4,3,2);

    $sum = 0;
    foreach ($x as $k=>$v) {
        $sum += $id[$k]*$v;
    }
    return (string)$y[$sum%11]===$id[count($id)-1];
}

var_dump(idcard_check('身份证号码 末尾如果是X要大写'));

2. 补充一个js版本

function idcard_check(id)
{
    if(!/^\d{18}$|^\d{17}X$/.test(id)) return false;

    var code  = [1,0,'X',9,8,7,6,5,4,3,2];
    var sum = 0;
    for(var i=17; i>0; i--){
        sum += id[17-i] * Math.pow(2,i)%11;
    }
    return id[17]==code[sum%11];
}

console.log(idcard_check('身份证号码 末尾X需大写 必须是字符串类型'));

以上就是身份证号码校验的内容,更多相关内容请关注PHP中文网(www.php.cn)!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn