Data Matrix Barcode split to different data

Viewed 26

I have a data matrix barcode that have the input

Data Matrix Barcode = 0109556135082301172207211060221967 21Sk4YGvF811210721

I wish to have output as below:-

Items Output
Gtin 09556135082301
Expire Date 21-07-22
Batch No 60221967
Serial No Sk4YGvF8
Prod Date 21-07-21

But My coding didn't detect after the space

$str = "0109556135082301172207211060221967 21Sk4YGvF811";

if ($str != null){
$ais = explode("_",$str);
for ($aa=0;$aa<sizeof($ais);$aa++)
{
    $ary = $ais[$aa];
    while(strlen($ary) > 0) {
        if (substr($ary,0,2)=="01"){
            $gtin = substr($ary,2,14);
            $ary = substr($ary,-(strlen($ary)-16));
        }

        else if (substr($ary,0,2)=="17"){
            $expirydate = substr($ary,6,2)."-".substr($ary,4,2)."-20".substr($ary,2,2);
            $ary = substr($ary,-(strlen($ary)-8));
        }
        else if (substr($ary,0,2)=="10"){
            $batchno = substr($ary,2,strlen($ary)-2);
            $ary = "";
        }
        else if (substr($ary,0,2)=="21"){
            $serialno = substr($ary,2,strlen($ary)-2);
            $ary = "";
        }
        else if (substr($ary,0,2)=="11"){
            $proddate = substr($ary,6,2)."-".substr($ary,4,2)."-20".substr($ary,2,2);
            $ary = substr($ary,-(strlen($ary)-8));
        }

        else {
            $oth = "";
        }
    }
}

My code output https://onecompiler.com/php/3yg6gs5ea didn't come out the result I expected. Anyway to modify it?

1 Answers

Solution

You can use a regex to make it short and easy.

Note

Your string does not contain all the characters of the code given in the description.

Code

$str             = "0109556135082301172207211060221967 21Sk4YGvF811210721";
$datePattern     = '/(\d\d)(\d\d)(\d\d)/';
$dateReplacement = '\3-\2-\1';
$matches         = [];

preg_match('/(?<gtin>.{18})(?<expire>.{6})(?<batch>.*?)\s(?<serial>.{12}(?<prod>.{6}))/', $str, $matches);
$matches['expire'] = preg_replace($datePattern, $dateReplacement, $matches['expire']);
$matches['prod']   = preg_replace($datePattern, $dateReplacement, $matches['prod']);
$matches           = array_filter($matches, fn($value, $key) => !is_numeric($key), ARRAY_FILTER_USE_BOTH);

$keyMap = [
    'gtin'   => 'Gtin',
    'expire' => 'Expire Date',
    'batch'  => 'Batch No.',
    'serial' => 'Serial No.',
    'prod'   => 'Production Date',
];

foreach ($keyMap as $key => $output) {
    echo "<tr><td>$output</td><td>{$matches[$key]}</td></tr>\n";
}

Output

<tr><td>Gtin</td><td>010955613508230117</td></tr>
<tr><td>Expire Date</td><td>21-07-22</td></tr>
<tr><td>Batch No.</td><td>1060221967</td></tr>
<tr><td>Serial No.</td><td>21Sk4YGvF811210721</td></tr>
<tr><td>Production Date</td><td>21-07-21</td></tr>
Related