Preg_match 表达式在字符串中查找代码
示例字符串:
$string = "Buyer must enter coupon code 10OFF100 in shopping cart.";
$string = "Get $20 Off Auto Parts Order Over $150. Use Coupon code: GAPCJ20";
我需要提取代码(10FF100
和 GAPCJ20
)。
我试图创建一个 preg_match
来查找“优惠券代码”和“优惠券代码:”并立即提取后面的短语或单词。我自己运气不好,也没有找到 reg 表达式。
请一些人发布正确的代码。
感谢您的帮助。
Example strings:
$string = "Buyer must enter coupon code 10OFF100 in shopping cart.";
$string = "Get $20 Off Auto Parts Order Over $150. Use Coupon code: GAPCJ20";
I need to extract the codes (10FF100
and GAPCJ20
).
I was trying to create a preg_match
to find "coupon code" and "coupon code:" and extract the phrase or word immediately after. Not having much luck myself or finding the reg expression.
Can some post the proper code please.
Thanks for the help.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
使用这个 php 代码:
输出
Use this php code:
OUTPUT
请尝试以下操作:
<代码>/优惠券代码[:]? ([\w]*)/i
Try the following:
/coupon code[:]? ([\w]*)/i
我的尝试:
My try:
对于您的第一个变体使用
对于第二个使用
For your first variant use
For the second use
我在下面做。
I do below.
这会将可选的
:
与预计由字母和数字组成的“代码”相匹配。这行吗?
简短的回答:不。
那么如何让它更有效率呢?最好的办法是将正则表达式与行字典进行匹配,其中包含您想要支持的许多示例和格式。然后不断完善您的正则表达式,直到获得 98% 可靠的正则表达式。我说 98% 是因为您可能会意识到它永远不会完美,因为有很多:
免费优惠券:输入此代码 8HFnF5
优惠券代码 (7859NhF)
优惠券多多!只需将 646GH4 放入您的购物篮
优惠码是797gGh
您的免费礼品代码是 4543G5
将代币“5479_G5t”添加到您的购物篮以获得免费 CD!
This will match optional
:
with a "code" which is expected to consist of alpha and numeric.Will this do?
Short answer: no.
So how to make it more efficient? Well the best thing to do would be to match a regex against a dictionary of lines that has many examples and formats you want to support. Then keep refining your regex until you get one that is 98% reliable. I say 98% because your probably come to the realization that it will never be perfect as there are so many:
Free Coupon: Enter this code 8HFnF5
Code for coupon (7859NhF)
Coupons galore! Just put 646GH4 in your basket
Cupon code is 797gGh
Your code for free goodies is 4543G5
Add token "5479_G5t" to your basket for free CD!