PHP 用于在字符串中插入特定字符串以打印 code128 条形码的正则表达式

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

为了使用 ZPL II 语言的 zebra 打印机打印 code128 条码,我正在尝试将一个字符串(这是我的条码)转换为一个新字符串。这个新字符串与一些与在 ALPHA 和 NUMERIC 模式之间切换相关的特定命令相同。切换到 NUMERIC 模式有助于使您的条形码更紧凑。 所以假设我要打印的条形码是:C00J025042101110823611001150119611 结果应该是这样的:

>:C00J>5025042101110823611001150119611

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

所以我正在寻找的是(如果可能的话)一个 REGEX,它将在我的字符串中插入 >5>6

这是另一个例子:

要打印的条码 = CJYJY10442101110S23611001150119611

要发送到打印机的字符串 = >:CJYJY1>50442101110>6S2>53611001150119611

一些更多的例子,以了解它是如何开始的。左边是要打印的条码,右边是发送到打印机的代码。

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

ZEBRA ZPL II 文档的额外注释:

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.

子集 C 是 NUMERIC,由“>6”调用

您可以将 preg_replace 与数组参数一起使用:

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

UPD

根据最后的评论,您可以尝试仅在找到对号时在模式之间切换。

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