我有一个数据库,其中包含用户用户输入的各种长度的条形码编号。
如何验证这些条形码值以确定格式是否正确,即长度和校验位?使用php
答案 0 :(得分:4)
你去:
function isValidBarcode($barcode) {
//checks validity of: GTIN-8, GTIN-12, GTIN-13, GTIN-14, GSIN, SSCC
//see: http://www.gs1.org/how-calculate-check-digit-manually
$barcode = (string) $barcode;
//we accept only digits
if (!preg_match("/^[0-9]+$/", $barcode)) {
return false;
}
//check valid lengths:
$l = strlen($barcode);
if(!in_array($l, [8,12,13,14,17,18]))
return false;
//get check digit
$check = substr($barcode, -1);
$barcode = substr($barcode, 0, -1);
$sum_even = $sum_odd = 0;
$even = true;
while(strlen($barcode)>0) {
$digit = substr($barcode, -1);
if($even)
$sum_even += 3 * $digit;
else
$sum_odd += $digit;
$even = !$even;
$barcode = substr($barcode, 0, -1);
}
$sum = $sum_even + $sum_odd;
$sum_rounded_up = ceil($sum/10) * 10;
return ($check == ($sum_rounded_up - $sum));
}
答案 1 :(得分:1)
我在项目中使用了PHPBarcodeChecker,看看这里:http://www.phpclasses.org/package/8560-PHP-Detect-type-and-check-EAN-and-UPC-barcodes.html
希望它有所帮助!