php - 如何在php中获取所有具有匹配文本的行
问题描述
我这里有一根绳子供练习。
$message = "Hurray! You've received a $100 Amazon Gift Card. Hope you enjoy this Amazon Gift Card! What's next? Apply the gift card to your Amazon account:=20 https://www.amazon.com/g/ Don't have an Amazon account? Sign up to redeem: www.amazon.com You can also redeem your gift card at checkout using this claim code: NE7N-TUD6NV-GUAB We hope to see you again soon, Amazon.com Once applied to your Amazon account, the entire amount will be added to you= r gift card balance. Your gift card balance can't be transferred to other a= ccounts, used to buy other gift cards, or, except as required by law, redee= med for cash. Your gift card balance will be applied automatically to eligible orders dur= ing the checkout process and when using 1-Click. If you don=E2=80=99t want = to use your gift card balance on your order, you can unselect it as a payme= nt method in checkout.=20 If you experience any issues using your gift card, you can reference your g= ift card by providing the following information to Customer Service: Order Number: 234343433433";
我想使用 preg_match 获取索赔代码,但我失败了。这是我的代码。
if(preg_match_all("/claim code:.*\s/", $message, $array)){
print_r($array);
}
输出是这样的
Array ( [0] => Array ( [0] => claim code: ) )
但我希望它显示索赔代码,有人可以帮忙吗?
解决方案
我会使用模式(?<=\bclaim code: )\S+
:
$message = "Hurray! You've received a $100 Amazon Gift Card. Hope you enjoy this Amazon Gift Card! What's next? Apply the gift card to your Amazon account:=20 https://www.amazon.com/g/ Don't have an Amazon account? Sign up to redeem: www.amazon.com You can also redeem your gift card at checkout using this claim code: NE7N-TUD6NV-GUAB We hope to see you again soon, Amazon.com Once applied to your Amazon account, the entire amount will be added to you= r gift card balance. Your gift card balance can't be transferred to other a= ccounts, used to buy other gift cards, or, except as required by law, redee= med for cash. Your gift card balance will be applied automatically to eligible orders dur= ing the checkout process and when using 1-Click. If you don=E2=80=99t want = to use your gift card balance on your order, you can unselect it as a payme= nt method in checkout.=20 If you experience any issues using your gift card, you can reference your g= ift card by providing the following information to Customer Service: Order Number: 234343433433";
preg_match_all("/(?<=\bclaim code: )\S+/", $message, $matches);
print_r($matches[0][0]);
这打印:
NE7N-TUD6NV-GUAB
您当前方法的主要问题是正则表达式模式本身。 \s*
匹配零个或多个空白字符,您应该使用\S*
我上面使用的代替。
推荐阅读
- c++ - 让 exe 确定其主机目录的路径
- python - 只有获得批准的用户才能在 django 中发布博客
- c - 如何在 CMake 构建中添加自定义标志
- reactjs - 在 try catch 块中使用 asysnc await 获取
- elasticsearch - 弹性现有查询对空字符串不起作用
- php - 登录问题后 Laravel 重定向
- javascript - 如何使循环等待用户操作并根据用户输入跳出循环
- android - 我正在创建 React 本机应用程序,我在 FlatList 上的打开弹出模式框中遇到问题
- spring-boot - 如何解决heroku部署期间的compileJava错误?
- r - 气隙环境 - 安装 R 包源与二进制文件