首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >构建航运注释的Regex

构建航运注释的Regex
EN

Stack Overflow用户
提问于 2019-11-20 21:13:30
回答 2查看 215关注 0票数 1
代码语言:javascript
复制
Shipped 1-95080 via other USPS with tracking 1Z2216FE0348543895.

Shipped 1-95080 via other FedEx with tracking 729870539581, 729870539592.

以下是两个单独的“注释”或输入到单个订单注释数据中的数据片段。

我需要搜索评论数据的“承运人”和个别跟踪号码,但他们的格式不同的格式取决于载体。

我们只使用2家航运公司USPS和FedEx进行包裹跟踪。我想要创建一个函数来提取载体类型,并从这些注释中只提取跟踪编号,以便将它们放在我们数据库中的各个位置,以便将来使用。我只是讨厌正则表达式。

有人有什么东西可以指引我走向正确的方向吗?(这也是PHP中的全部内容)

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2019-11-20 23:29:10

我读过你说过恨雷杰普,但这可能对这个案子有用。我写了一个能帮你的例子。

第一句:

代码语言:javascript
复制
<?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'

?>

第二个是:

代码语言:javascript
复制
<?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将捕获三个组:

(?P<ship_num>\d{1}\-\d+)这个组将捕获一个数字(\d)、一个连字符(\-)和一些数字(\d+)。

(?P<company>\w+)这个组只会捕获一些字母字符(\w+)。

(?<tracking_code>[\w,\s]+)最后,这个组将捕获一些空格字符(\s)、逗号和字母字符(\w)。

在所有这些组中,我给每个组命名(?P<group name>)。

工具Regex101可以用于测试RegExp。

票数 3
EN

Stack Overflow用户

发布于 2019-11-20 21:18:52

如果格式总是相同的,您可能会将strpos()substr()结合在一起。

考虑到您的注释在字符串中总是有'USPS‘或'FedEx’,只需在strpos()中使用一个条件即可。在这种情况下,您可能需要使用绞线器()来确保大小写匹配:

代码语言:javascript
复制
if (strpos(strtoupper($yourCommentString), 'USPS') !== false)
    $carrier = 'USPS';
else
    $carrier = 'FedEx';

至于跟踪数字,我找到了一种不需要正则表达式的解决方案,假设数字总是跟随“跟踪”,并由“,”分隔:

代码语言:javascript
复制
$string = 'Shipped 1-95080 via other USPS with tracking 1Z2216FE0348543895, 1Z2216FE0348543895';

$start = strpos($string, 'tracking ') + strlen('tracking ');
$trackString = substr($string, $start);

$allTrack = explode(', ', $trackString);
票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/58963469

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档