2017-03-09 19 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列を解析します)。入力文字列を想定し

$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'; 
} 

。関数(必要な範囲1-12からすべての数字が繰り返さ存在しないかどうかをチェックする)
array_diff

+0

申し訳ありませんが、ここでコードを投稿したときの間違いがあります - ')'があり、私は質問を更新します。 –

+1

それでは、問題は何ですか? それは私の最後に働いています - https://regex101.com/r/0wzQ6a/2 –

0

は有効である(すべての条件が満たされている)、それは112からitem[]すべての値に含まれている場合、このコードのシンプルな作品はよりも速く動作しますと理解しやすいです:

// 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) 
関連する問題