문제

I am trying to solve an issue with a function stripos in PHP. We are doing promo codes and for instance, one promo code is "friends" and another is "friends40" and when someone types that in, it is saying that both of these are true so it will give them a double discount.

We need these to be distinct but not case sensitive. Is there a technique or another function we can use?

if (stripos($promo,'friends') !== false) {   
$price = $price/2;
$adddiscount = .50;
}
if (stripos($promo,'FRIENDS40') !== false) {   
$price = $price - $price * .4;
$adddiscount = .4;
}
도움이 되었습니까?

해결책

Both will validate as stripos is case-insensitive and friends can be found in FRIENDS40. You need to do the FRIENDS40 check first then the friends

<?php
if(stripos($promo,'FRIENDS40') !== false) {   
    $price = $price - $price * .4;
    $adddiscount = .4;
}elseif(stripos($promo,'friends') !== false) {   
    $price = $price/2;
    $adddiscount = .50;
}

An alternative would be to use strpos() which IS case-sensitive:

<?php
if(strpos($promo,'FRIENDS40') !== false) {   
    $price = $price - $price * .4;
    $adddiscount = .4;
}
if(strpos($promo,'friends') !== false) {   
    $price = $price/2;
    $adddiscount = .50;
}

To be on the safe side I would recommend using the first method.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top