Reputation: 15
I tried so many preg_replace and preg_match codes but i cant do. I try to find strings contain +18 , 18+ or (+18) I cant explain but you can understand when see my codes.
//inputs
$product='example: 18 kg apple'; // my hope output: EVERYONE
$product='water pipe (18) meters'; // my hope output: EVERYONE
//outputs: OVER 18
$product='product +18 dress'; // my hope output: OVER 18
$product='product 18+ dress'; // my hope output: OVER 18
$product='product (+18) dress'; // my hope output: OVER 18
//outputs are already OVER 18
//Because of contain 18
//not +18 or 18+. it doesnt work truly
preg_match('/\b(\w*18\w*)\b/', $product, $match);
if( $match[1]=='+18' || $match[1]=='18+' ) {
echo "OVER 18<br>";
}
else{
echo "EVERYONE<br>";
}
Upvotes: 0
Views: 88
Reputation: 15629
In this simple case, I wouldn't use an regex. Just using strpos
would also do the job.
if (strpos($product, '18+') !== false || strpos($product, '+18') !== false) {
// over 18
}
Upvotes: 0
Reputation: 3178
Use this: (\+18|18\+)
- it checks if +18
or 18+
exists in the string.
So something like this:
preg_match('(\+18|18\+)', $product, $match);
should work.
Only tested it here https://regex101.com/ (a very good place to test regexp
Upvotes: 1