gpt4 book ai didi

php - 如何验证 VIN 号码?

转载 作者:IT王子 更新时间:2023-10-29 00:11:16 28 4
gpt4 key购买 nike

如何验证 Vehicle Identification Number用PHP?我只需要检查输入的 VIN 号码是否正确。

最佳答案

这是我使用维基百科文章中的示例快速编写的内容。

不保证完美或无错误或 super 高效,但应该为您提供一个坚实的起点:

注意:我包含了 Confluence 提供的编辑下面,使程序稍微更简洁。

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 时存在小百分比错误:

...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 将根据上述过程进行验证。是否要检查由您决定:

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 号码?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3831764/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com