Shipped 1-95080 via other USPS with tracking 1Z2216FE0348543895.
Shipped 1-95080 via other FedEx with tracking 729870539581, 729870539592.
这里有两个单独的“注释”或输入到单个订单注释数据中的数据。
我需要在评论数据中搜索“载体”和各个跟踪号,但它们的格式因载体而异。
我们仅使用2个货运公司USPS和FedEx进行包裹跟踪。我想创建一个函数来提取承运人类型,并仅从这些注释中提取跟踪号,以将其放置在数据库中的各个位置,以备将来使用。我只是讨厌正则表达式。
有人有什么可以向我指出正确的方向吗? (而且这全在PHP中)
我看过您说的讨厌regexp,但对这种情况可能有用。我写了一个可以帮助您的示例。
至第一个短语:
<?php
$string = 'Shipped 1-95080 via other USPS with tracking 1Z2216FE0348543895.';
preg_match('/.+(?P<ship_num>\d{1}\-\d+).+via other (?P<company>\w+) with tracking (?<tracking_code>[\w,\s]+)/', $string, $match);
if(strpos($match['tracking_code'], ',')!==false) {
$match['tracking_code'] = array_map(function($index) {
return trim($index);
}, explode(',', $match['tracking_code']));
}
echo $match['ship_num']; // this echo prints '1-95080'
echo $match['company']; // this echo prints 'USPS'
print_r($match['tracking_code']); // this print_r prints an array with the value '1Z2216FE0348543895'
?>
和第二个:
<?php
$string = 'Shipped 1-95080 via other FedEx with tracking 729870539581, 729870539592.';
preg_match('/.+(?P<ship_num>\d{1}\-\d+).+via other (?P<company>\w+) with tracking (?<tracking_code>[\w,\s]+)/', $string, $match);
if(strpos($match['tracking_code'], ',')!==false) {
$match['tracking_code'] = array_map(function($index) {
return trim($index);
}, explode(',', $match['tracking_code']));
}
echo $match['ship_num']; // this echo prints '1-95080'
echo $match['company']; // this echo prints 'FedEx'
print_r($match['tracking_code']); // this print_r prints an array with the values '729870539581' and '729870539592'
?>
此RegExp将捕获3个组:
(?P<ship_num>\d{1}\-\d+)
该组将捕获一个数字(\d
),一个连字符(\-
)和一些数字(\d+
)。
(?P<company>\w+)
该组将仅捕获一些字母字符(\w+
)。
(?<tracking_code>[\w,\s]+)
最后,该组将捕获一些空格字符(\s
),逗号和字母字符(\w
)。
在所有这些组中,我分别命名了每个组[?P<group name>
。
Regex101工具可能对测试RegExp有用。>