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

时间:2014-12-03 19:13:30

标签: php regex

您能否告诉我为什么过度测试不起作用并且可能提供解决方案?我想做的是3件事首先得到折扣类型(免费送货,百分比或金钱)折扣金额£x或x%,最后折扣的条件是基于你花费超过£x或第一个订单

非常感谢任何帮助。

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 ."\n\n";
}

1 个答案:

答案 0 :(得分:1)

1。)用" regex101.com"进行测试。 - > http://regex101.com/r/zR8xR2/1

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