PHP验证德国税务ID(Steueridentifikationsnummer)

德国税务标识(
Steueridentifikationsnummer)具有以下属性:

>它有11位数字
>第一个数字不能为0
>在前十位数字中:一个数字恰好出现两次或三次,一个或两个数字出现零次,其他数字出现一次
>最后一位是校验和Example Code for Checksum

第三个要点对我来说有点难以以优雅的方式解决.我已经有了其他三个要点的代码,但是很想得到最后一个的输入,所以这对其他人来说可能是一个小小的参考.

# validate tax number
        $taxNumber = $_POST['taxNumber'];
        echo preg_replace("/[^0-9]/", "", $taxNumber);

        if (strlen($taxNumber != 11)) {
            # 11 digits
            $taxNumberValid = false;
        } else if ($taxNumber[0] == "0") {
            # first digit != 0
            $taxNumberValid = false; 
        } else {
            # one digit two times, one digit zero times


            # checksum
            $numbers = str_split($taxNumber);
            $sum = 0;
            $product = 10;
            for ($i = 0; $i <= 9; $i++) {
                $sum = ($numbers[$i] + $product) % 10;
                 if ($sum == 0) {
                     $sum = 10;
                 }
                 $product = ($sum * 2) % 11;
            }
            $checksum = 11 - $product;
            if ($checksum == 10) {
                $checksum = 0;
            }

            if ($taxNumber[10] != $checksum) {
                $taxNumberValid = false;
            }
        }

最佳答案 此代码解决了以下问题:

// remove whitespaces, slashes & other unnecessary characters
$taxNumber = preg_replace("/[^0-9]/", "", $taxNumber);

// by default the taxnumber is correct
$taxNumberValid = true;

// taxnumber has to have exactly 11 digits
if (strlen($taxNumber) != 11) {
    $taxNumberValid = false;                
}

// first digit cannot be 0
if ($taxNumber[0] == "0") {
    $taxNumberValid = false; 
} 

/* 
 make sure that within the first ten digits:
     1.) one digit appears exactly twice or thrice
     2.) one or two digits appear zero times
     3.) and oll other digits appear exactly once once
*/
$digits = str_split($taxNumber);
$first10Digits = $digits;
array_pop($first10Digits);
$countDigits = array_count_values ($first10Digits);
if (count($countDigits) != 9 && count($countDigits) != 8) {
    $taxNumberValid = false;
}

// last check: 11th digit has to be the correct checkums
// see http://de.wikipedia.org/wiki/Steueridentifikationsnummer#Aufbau_der_Identifikationsnummer
$sum = 0;
$product = 10;
for($i = 0; $i <= 9; $i++) {
    $sum = ($digits[$i] + $product) % 10;
     if ($sum == 0) {
         $sum = 10;
     }
     $product = ($sum * 2) % 11;
}
$checksum = 11 - $product;
if ($checksum == 10) {
    $checksum = 0;
}
if ($taxNumber[10] != $checksum) {
    $taxNumberValid = false;
}

2017年更新

直到2016年,规则是,在前十位数内,一个数字必须恰好出现两次.

从2017年开始,规则是,在前十位数字内,一个数字必须恰好出现两次或三次.

点赞