2014-12-03 69 views
0

您能否告诉我为什么过度测试不起作用并且可能提供解决方案?我想要做的是3件事首先获得折扣类型(免费送货,百分比或折扣)折扣金额£x或x%,最后是折扣基于您花费超过£x时的金额或您的第一笔订单。php正则表达式可以从字符串中获得3个变量值

任何帮助将不胜感激。

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

1)与 “regex101.com” 测试 - >http://regex101.com/r/zR8xR2/1

2) “return $matches;” - > “return $matches[1];

+0

非常有用的工具,非常感谢你:) – 2014-12-04 07:37:06