繁体   English   中英

按数字格式拆分数字

[英]Split Number by a number format

我真的想得太久了,找不到做这件事的逻辑/算法。 然后我只使用 if else 但我知道这很糟糕,因为会有太多的陈述。

我有下面的数字格式组来拆分输入数字:

  • 01(此数字格式后得到14位数字)
  • 3101(此数字格式后获得6位数字)
  • 3102(获得6位数字)
  • 3202(获得6位数字)
  • 13(得到6位数)
  • 15(得到6位数)
  • 11(得到6位数)
  • 21(得到其余的)

一些规则

  • 01 总是在第一个序列
  • 21 总是在最后一个序列
  • 除 01 和 21 之外的其他数字格式可以在任何序列位置。
  • 相同的前缀号码格式不能重复

例如,输入编号: 01 00690085173067 3102 002000 13 191004 21 191004091395

结果应该是:

01 : 00690085173067
3102 : 002000
13 : 191004
21 : 191004091395

目前我只使用 IF ELSE 语句来获取后面的数字。

这是我使用 PHP 的代码片段。 此代码只能处理上面的示例输入。 根据规则可能会有其他序列号格式,但如果只使用这样的 if else 语句会很困难。

$first = substr($input, 0, 2);
if ($first == 01) { 

    $itemCode =  substr($input, 2, 14); // get the 6 digits after 01
    $second = substr($input, 16, 4);

    if ($second == 3102) { 
        $quantity =  substr($input, 20, 6);  // get the 6 digits after 3102
        $third = substr($input, 26, 2);
        if ($third == 13) { 
           $packedDate =  substr($input, 28, 6); // get the 6 digits after 13
            $fourth = substr($input, 34, 2);  
            if ($fourth == 21) {
                $serialNumber =  substr($scanner, 36); // get the rest number after 21
            } 
       }
   }
}

有什么好的办法可以解决这个问题吗?

如果前缀不会重复,您可以使用preg_match_all将前缀与其每个尾随数字匹配,使用array_combine创建由其前缀索引的数字数组:

$input = '010069008517306731020020001319100421191004091395';

if (preg_match_all('/(01)(\d{14})|(310[12]|3202|1[135])(\d{6})|(21)(\d+)/', $input, $matches)) {
    $numbers = array_filter(array_combine($matches[1], $matches[2]) + 
                            array_combine($matches[3], $matches[4]) + 
                            array_combine($matches[5], $matches[6]));
    print_r($numbers);
}
else {
    echo "Invalid input!";
}

输出:

Array
(
    [01] => 00690085173067
    [3102] => 002000
    [13] => 191004
    [21] => 191004091395
)

3v4l.org 上的演示

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM