2016-02-05 146 views
1

我有下面的職位領域提交,我想獲得每個數字在表單字段的數量值。有人可以幫助我的正則表達式?我試圖讓每個數字都在一個變量中。preg_match /正則表達式格式需要

FORMAT

Quantity_{Category}_{Product}_{Item} 

發佈字段提交

[submitted] => 1 
[Quantity_12038_16061_24960] => 1 
[Quantity_12037_16060_24959] => 2 
[btnBuyNow] => Next Step 

PHP代碼

foreach ($_POST as $key => $value) { 
    if (preg_match('/^Quantity_(\d+)$/', $key, $matches)) { 
     echo 'Key:' . $key . '<br>'; 
     echo 'Matches:' . $matches . '<br>'; 
     echo '<hr>'; 
    } 
} 

回答

2

使用preg_match()docs爲了這個目的,那就是代碼將如何看起來像一個樣本:

$subject="Quantity_12038_16061_24960"; 
$pattern='/Quantity_(\d+)_(\d+)_(\d+)/'; 
preg_match($pattern, $subject, $matches); 

echo $matches[0]; //12038 {Category} 
echo $matches[1]; //16061 {Product} 
echo $matches[2]; //24960 {Item} 

你可以看到這個正則表達式是如何執行的here

+1

感謝它很接近,但我能夠解決它。下面是輸出,所以我不得不調整它拉選自1,2和3,而不是0。 \t陣列 \t( \t [0] => Quantity_12038_16061_24960 \t [1] => 12038 \t [2 ] => 16061 \t [3] => 24960 \t) –

1

由於問題陳述,不需要正則表達式:

foreach($_POST as $key => $val) { 
    if(strpos($key, 'Quantity') === 0) { 
     $results = explode('_', $key); 
     print_r($results); 
    } 
} 

爲了擺脫數量串無論出於何種原因只是unset($results[0]);的。