IMEI验证功能

Vla*_*tev 3 php function imei

有人知道用于IMEI验证的PHP函数吗?

ryb*_*111 5

简短解决方案

你可以使用这个(巫术!)解决方案,只需检查字符串长度:

function is_luhn($n) {
    $str = '';
    foreach (str_split(strrev((string) $n)) as $i => $d) {
        $str .= $i %2 !== 0 ? $d * 2 : $d;
    }
    return array_sum(str_split($str)) % 10 === 0;
}
function is_imei($n){
    return is_luhn($n) && strlen($n) == 15;
}
Run Code Online (Sandbox Code Playgroud)

详细解决方案

这是我原来的功能,解释了每一步:

function is_imei($imei){
    // Should be 15 digits
    if(strlen($imei) != 15 || !ctype_digit($imei))
        return false;
    // Get digits
    $digits = str_split($imei);
    // Remove last digit, and store it
    $imei_last = array_pop($digits);
    // Create log
    $log = array();
    // Loop through digits
    foreach($digits as $key => $n){
        // If key is odd, then count is even
        if($key & 1){
            // Get double digits
            $double = str_split($n * 2);
            // Sum double digits
            $n = array_sum($double);
        }
        // Append log
        $log[] = $n;
    }
    // Sum log & multiply by 9
    $sum = array_sum($log) * 9;
    // Compare the last digit with $imei_last
    return substr($sum, -1) == $imei_last;
}
Run Code Online (Sandbox Code Playgroud)