UPS跟蹤號校驗代碼

每一個快遞公司生成的單號大部分帶自校驗功能。下面的代碼實現對UPS單號的正確性校驗php

function validUPS($tr){
    $tr = strtoupper(trim($tr));
    if (strlen($tr) == 11)
    {
        $checknumber = 100 - (substr($tr,1, 1) + substr($tr,3, 1) + substr($tr,5, 1) + substr($tr,7, 1) + substr($tr,9, 1) + 2 * (substr($tr,2, 1) + substr($tr,4, 1) + substr($tr,6, 1) + substr($tr,8, 1)));
        if ($checknumber < 0)
        {
            $checknumber = 100 + $checknumber;
        }
        if ($checknumber >= 10)
        {
            $checknumber = substr($checknumber,1,1);
        }
        else if ($checknumber <= 10)
        {
            $checknumber = substr($checknumber,0,1);
        }
        $r= substr($tr,10, 1) == $checknumber;
    }else if (strlen($tr)=='18'){
        $tr = substr($tr,2, 16);
        for ($i = 65; $i <= 90; $i++)
        {
            if ($i >= 65 && $i <= 72)
            {
                $tr=str_replace(chr($i),chr($i-15),$tr);
            }
            else if ($i >= 73 && $i <= 82)
            {
                $tr=str_replace(chr($i),chr($i-25),$tr);
            }
            else if ($i >= 83 && $i <= 90)
            {
                $tr=str_replace(chr($i),chr($i-35),$tr);
            }
        }
        $checknumber = 100 - (substr($tr,0, 1) + substr($tr,2, 1) + substr($tr,4, 1) + substr($tr,6, 1) + substr($tr,8, 1) + substr($tr,10, 1) + substr($tr,12, 1) + substr($tr,14, 1) + 2 * (substr($tr,1, 1) + substr($tr,3, 1) + substr($tr,5, 1) + substr($tr,7, 1) + substr($tr,9, 1) + substr($tr,11, 1) + substr($tr,13, 1)));
        if ($checknumber < 0)
        {
            $checknumber = 100 + $checknumber;
        }
        if ($checknumber < 10)
        {
            $checknumber = substr($checknumber,0,1);
        }
        else if ($checknumber >= 10)
        {
            $checknumber = substr($checknumber,1,1);
        }
        $r= $checknumber == substr($tr,15, 1);
    }else {
        $r=false;
    }
    return $r;
}
相關文章
相關標籤/搜索