[英]Split Number by a number format
我真的想得太久了,找不到做这件事的逻辑/算法。 然后我只使用 if else 但我知道这很糟糕,因为会有太多的陈述。
我有下面的数字格式组来拆分输入数字:
一些规则:
例如,输入编号: 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
)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.