2014-12-03 20 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

相關問題