PHP VIN号码验证码 [英] PHP VIN number validation code

查看:130
本文介绍了PHP VIN号码验证码的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有人知道用PHP编写的Vehicle Identification Number( Wiki )验证代码吗?我只需要检查输入的vin号码是否正确?

Does anyone know any Vehicle Identification Number (wiki) validation code written in PHP? I just need to check if the entered vin number is correct or not?

推荐答案

以下是我使用维基百科文章中的示例快速写出的东西.

Here's something I wrote up real quick using the example in the wikipedia article.

不能保证是完美的,没有错误的或超级有效的,但应该为您提供一个坚实的起点:

Not guaranteed perfect or bug free or super efficient, but should provide you with a solid starting point:

注意:我加入了

Note: I included the edits provided by Confluence below, making the procedure slightly more succinct.

function validate_vin($vin) {

    $vin = strtolower($vin);
    if (!preg_match('/^[^\Wioq]{17}$/', $vin)) { 
        return false; 
    }

    $weights = array(8, 7, 6, 5, 4, 3, 2, 10, 0, 9, 8, 7, 6, 5, 4, 3, 2);

    $transliterations = array(
        "a" => 1, "b" => 2, "c" => 3, "d" => 4,
        "e" => 5, "f" => 6, "g" => 7, "h" => 8,
        "j" => 1, "k" => 2, "l" => 3, "m" => 4,
        "n" => 5, "p" => 7, "r" => 9, "s" => 2,
        "t" => 3, "u" => 4, "v" => 5, "w" => 6,
        "x" => 7, "y" => 8, "z" => 9
    );

    $sum = 0;

    for($i = 0 ; $i < strlen($vin) ; $i++ ) { // loop through characters of VIN
        // add transliterations * weight of their positions to get the sum
        if(!is_numeric($vin{$i})) {
            $sum += $transliterations[$vin{$i}] * $weights[$i];
        } else {
            $sum += $vin{$i} * $weights[$i];
        }
    }

    // find checkdigit by taking the mod of the sum

    $checkdigit = $sum % 11;

    if($checkdigit == 10) { // checkdigit of 10 is represented by "X"
        $checkdigit = "x";
    }

    return ($checkdigit == $vin{8});
}

注意:由于校验和的性质,验证VIN时会出现很小的百分比错误:

Note: there is a small percent error with verifying VINs because of the nature of the checksum:

...匹配并不能证明VIN是正确的,因为任意两个不同的VIN仍具有匹配的校验位,这仍然是十分之一的可能性.

...a match does not prove the VIN is correct, because there is still a 1 in 11 chance of any two distinct VINs having a matching check digit.

也请注意:11111111111111111将按照上述步骤进行验证.您是否要检查取决于您自己:

Also note: 11111111111111111 will validate against the procedure above. Whether or not you want to check for that is up to you:

直数(连续17个连续的1)足以满足校验位.这是因为值1乘以89(权重之和)仍为89.89%11为1,即校验位.这是测试VIN检查算法的简便方法.

Straight-ones (seventeen consecutive '1's) will suffice the check-digit. This is because a value of one, multiplied against 89 (sum of weights), is still 89. And 89 % 11 is 1, the check digit. This is an easy way to test a VIN-check algorithm.

参考: http://en.wikipedia.org/wiki/Vehicle_identification_number#Check_digit_calculation

这篇关于PHP VIN号码验证码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆