Search code examples
phppreg-matchpreg-match-all

Why is my preg_match_all not working?


I am using preg_match_all to ensure that a string follows a certain pattern.

It should display 'all conditions are met' becuase the string follows the pattern, but instead, it displays 'conditions net met'.

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

Solution

  • The right way would be using
    parse_str(to parse quesry string: key/value pairs separated with &)
    and array_diff(to check if all numbers from the needed range 1-12 are present and not repeated) functions:

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