开发者

Preg_match expression to find code in string

Example strings:

$string = "Buyer must enter coupon code 10OFF100 in shopping cart.";
$string = "Get $20 Off Auto开发者_JS百科 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.


Use this php code:

$arr = array("Buyer must enter coupon code 10OFF100 in shopping cart.", "Get $20 Off Auto Parts Order Over $150. Use Coupon code: GAPCJ20");
foreach ($arr as $s) {
   preg_match('~coupon code\W+(\w+)~i', $s, $m);
   var_dump($m[1]);
}

OUTPUT

string(8) "10OFF100"
string(7) "GAPCJ20"


Try the following: /coupon code[:]? ([\w]*)/i


My try:

<?php
if (preg_match('/coupon code:?\s+(.+)(\s+|$)/', $str, $matches)) {
  list(, $code) = $matches;
  echo $code;
}


For your first variant use

Buyer must enter coupon code ([^ ]*) in shopping cart.

For the second use

Get $20 Off Auto Parts Order Over $150. Use Coupon code: (.*)


I do below.

preg_match('/[Cc]oupon code:?(\w+)/',$string,$match);


This will match optional : with a "code" which is expected to consist of alpha and numeric.

/coupon code:? ([a-z0-9]+)/i

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:

  • Possible miss-spellings
  • Coupon codes using different characters sets
  • Variation of sentences and ordering of words i.e.
    • 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!
    • ... all of these will fail with the above regex
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜