2017-03-09 25 views
1

我正在使用preg_match_all以確保字符串遵循特定模式。爲什麼我的preg_match_all不能正常工作?

由於字符串遵循該模式,它應該顯示'所有條件都滿足',但是它會顯示'條件淨滿足'。

$order = "item[]=2&item[]=1&item[]=3&item[]=4&item[]=5&item[]=6&item[]=7&item[]=8&item[]=9&item[]=10&item[]=11&item[]=12"; 
$pattern = "/^(item\[\]=([1-9]|10|11|12))(&(item\[\]=([1-9]|10|11|12))){11}$/"; 

if(preg_match($pattern, $order)) { 

    // check for repetition 
    $matches = []; 
    preg_match_all("/\d+/", $order, $matches); 
    if(count(array_count_values($matches[0])) == 12) { 
     // All are unique values 
     echo 'All conditions met'; 
    } 
}else{ 
    echo 'Conditions not met'; 
} 
+0

您的'$ pattern'正則表達式不完整,您發佈了正在使用的正則表達式嗎? –

+3

您的輸入字符串看起來像查詢字符串。我會使用['parse_str()'](http://php.net/manual/en/function.parse-str.php)將值放入一個數組,然後檢查數組的約束。這很容易。 – axiac

+0

這是一個類似的故事http://stackoverflow.com/questions/42679522/make-sure-that-string-follows-the-required-format並從@AbraCadaver有解決方案。你應該學習和使用'parse_str'函數 – RomanPerekhrest

回答

1

正確的方式將使用
parse_str(解析quesry串:與&分隔的鍵/值對)
array_diff(以檢查是否從所需要的範圍1-12的所有數字都存在並且沒有重複的)功能:

$order = "item[]=2&item[]=1&item[]=3&item[]=4&item[]=5&item[]=6&item[]=7&item[]=8&item[]=9&item[]=10&item[]=11&item[]=12"; 
parse_str($order, $items); 

if (isset($items['item']) && is_array($items['item']) 
    && count($items['item']) == 12 && !array_diff(range(1, 12), $items['item'])) { 
    echo 'All conditions met'; 
} else { 
    echo 'Conditions not met'; 
} 
+0

感謝羅馬人,我更喜歡這個解決方案比使用正則表達式。 –

+0

@TheCodesee,歡迎 – RomanPerekhrest

+0

我應該張貼這個答案也http://stackoverflow.com/questions/42679522/make-sure-that-string-follows-the-required-format/或者你想嗎? –

0

試試這個:

<?php 

$order = "item[]=2&item[]=1&item[]=3&item[]=4&item[]=5&item[]=6&item[]=7&item[]=8&item[]=9&item[]=10&item[]=11&item[]=12"; 
$pattern = "/^(item\[\]=([1-9]|10|11|12))(&(item\[\]=([1-9]|10|11|12))){11}$/"; 

if(preg_match($pattern, $order)) { 

    // check for repetition 
    $matches = []; 
    preg_match_all("/\d+/", $order, $matches); 
    if(count(array_count_values($matches[0])) == $movienumber) { 
     // All are unique values 
     echo 'All conditions met'; 
    } 
}else{ 
    echo 'Conditions not met'; 
} 

你失蹤的模式的)

+0

對不起,這只是一個錯誤,當我在這裏發佈代碼 - ')'在那裏,我會更新我的問題。 –

+1

那麼最新的問題? 它在我的工作 - https://regex101.com/r/0wzQ6a/2 –

0

假定輸入字符串是有效的(所有條件都滿足),當它含有item[]所有從1值以12,這個簡單的代碼作品比更快它更容易理解:

// Input string 
$order = "item[]=2&item[]=1&item[]=3&item[]=4&item[]=5&item[]=6&item[]=7&item[]=8&item[]=9&item[]=10&item[]=11&item[]=12"; 

// Parse it to values and store them in $pieces 
$pieces = array(); 
parse_str($order, $pieces); 

// Need to sort the values to let the comparison succeed 
sort($pieces['item']); 
$valid = ($pieces['item'] == range(1, 12)); 

// Verification 
var_dump($valid); 
// It prints: 
// bool(true)