douqian2957 2014-12-03 19:13
浏览 45
已采纳

php Regex模式从字符串中获取3个变量值

Can you please tell me why the over test won't work and perhaps offer a solution? What I am trying to do is 3 things firstly get the discount type (free delivery, percentage or money off) discount amount £x or x% and lastly the condition the discount is based on when you spend over £x or on your first order.

Any help would be greatly appreciated.

function discountType($val) {
    // find the discount type if any..
    $val = strtolower($val);

    if(strpos($val,'%') !== false) {
        return 'Percentage';
    }

    if(strpos($val,'£') !== false) {
            return 'Money';
    }

    if(strpos($val,'£') !== false) {
            return 'Money';
    }

    if(strpos($val,'save £') !== false || strpos($val,'save £')) {
        return 'Save';
    }

    if(strpos($val, 'free delivery') !== false) {
        return 'Delivery';
    }

    if(strpos($val, 'free uk delivery') !== false) {
        return 'Delivery';
    }

    return '';
}

function discountCondition($val) {
    $val = strtolower($val);
    if(preg_match('/over £ (\d+)/i', $val, $matches)){
        return $matches;
    }

    if(preg_match('/spend £ (\d+)/i', $val, $matches)){
        return $matches[2];
    }

    if(preg_match('/(\d+) or more/i', $val, $matches)){
        return $matches[1];
    }
}

function discountAmount($val) {

if (preg_match('/(\d+%)/i', $val, $matches)) {
    return $matches[1];
}

if (preg_match('/(?:£|£)(\d+)/i', $val, $matches)) {
    return $matches[1];
}

if(preg_match('/(save)\s+(?:£|£)(\d+)/i', $val, $matches)){
    return $matches[1];
}

if (preg_match('/free( uk)? delivery/i', $val)) {
        return 'Free Delivery';
}
}

$tests = [];
$tests[0] = 'Get 15% off any purchase of £75 or more at GalaxyPerfume.co.uk';
$tests[1] = '£5 off for your first order over £40';
$tests[2] = '£6 off when you spend £30 or more';
$tests[3] = '£10 OFF ALL ORDERS OVER £150';
$tests[4] = '£10 off when you spend over £100. Enter ‘******’ at the checkout';

foreach($tests as $test){

    $discount_type = discountType($test);
    $discount_amount = discountAmount($test);
    $discount_condition = discountCondition($test);

    echo "discount_type = ". $discount_type ." discount_amount = ". $discount_amount ." discount_condition = ". $discount_condition ."

";
}
  • 写回答

1条回答 默认 最新

  • dougu2240 2014-12-03 19:36
    关注

    1.) test it with "regex101.com" -> http://regex101.com/r/zR8xR2/1

    2.) "return $matches;" -> "return $matches[1];"

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 求差集那个函数有问题,有无佬可以解决
  • ¥15 【提问】基于Invest的水源涵养
  • ¥20 微信网友居然可以通过vx号找到我绑的手机号
  • ¥15 寻一个支付宝扫码远程授权登录的软件助手app
  • ¥15 解riccati方程组
  • ¥15 display:none;样式在嵌套结构中的已设置了display样式的元素上不起作用?
  • ¥15 使用rabbitMQ 消息队列作为url源进行多线程爬取时,总有几个url没有处理的问题。
  • ¥15 Ubuntu在安装序列比对软件STAR时出现报错如何解决
  • ¥50 树莓派安卓APK系统签名
  • ¥65 汇编语言除法溢出问题