Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 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.

like image 303
user756119 Avatar asked Feb 28 '26 22:02

user756119


1 Answers

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"
like image 112
anubhava Avatar answered Mar 02 '26 12:03

anubhava