Search code examples
phpzpl-iicode128

PHP Regex to insert specific strings in a string in order to print a code128 barcode


in order to print a code128 barcode with a zebra printer in ZPL II language, i'm trying to convert a string (which is my barcode) into a new string. This new string is the same string with some specific commands related to switching between ALPHA and NUMERIC modes. Switching to NUMERIC mode helps making your barcode more compact. so lets say the barcode i want to print is : C00J025042101110823611001150119611 the result should be this :

>:C00J>5025042101110823611001150119611

>: mean we Start in ALPHA
>5 Mean we switch from ALPHA to NUMERIC ONLY
>6 Mean we switch from NUMERIC to ALPHA

So what i'm looking for is (if possible) a REGEX which will insert >5 or >6 in my string.

here is another example:

barcode to print = CJYJY10442101110S23611001150119611

String to send to printer = >:CJYJY1>50442101110>6S2>53611001150119611

Some more example, in order to understand how it starts. On the left the barcode to print, on the right the code sent to the printer.

C000025042101110823611001150119611 >:C0>500025042101110823611001150119611 CJ00025042101110823611001150119611 >:CJ>500025042101110823611001150119611 C0J0025042101110823611001150119611 >:C0J0>5025042101110823611001150119611 C00J025042101110823611001150119611 >:C00J>5025042101110823611001150119611 C000J25042101110823611001150119611 >:C000J2>55042101110823611001150119611 C0000J5042101110823611001150119611 >:C>50000>6J>55042101110823611001150119611 C00000J042101110823611001150119611 >:C0>50000>6J0>542101110823611001150119611

Extra note from the ZEBRA ZPL II documentation:

Code 128 subsets A and C are programmed as pairs of digits, 00-99, in the field data string. [...] in subset C, they are printed as entered. NOTE: Non-integers programmed as the first character of a digit pair (D2) are ignored. However, non-integers programmed as the second character of a digit pair (2D) invalidate the entire digit pair, and the pair is ignored. An extra, unpaired digit in the field data string just before a code shift is also ignored.

Subset C is NUMERIC, invoked by ">6"


Solution

  • You can use preg_replace with array arguments:

    $result = preg_replace(
        array(
            '/(^\D)/',
            '/(\D)(\d)/',
            '/(\d)(\D)/',
        ),
        array(
            '>:$1',
            '$1>5$2',
            '$1>6$2',
        ),
        $code
    );
    

    UPD

    According to the last comments you can try to switch between modes only if pair numbers found.

    $result = preg_replace(
        array(
            '/(^\D)/',
            '/((?:\d{2})+)/',
            '/\>[56]$/',
        ),
        array(
            '>:$1',
            '>5$1>6',
            '',
        ),
        $code
    );