Search code examples
phparrayspreg-replacesubstr

Make sure that string follows the required format


I am attempting to check if a string follows a certain format by checking that:

  • item[]= is repeated four times
  • item[]= is followed by a number and & symbol (e.g item[]=2&), except the last number doesn't have & after it
  • The numbers after item[]= consist of only either 1-4 and can be in any order, but not repeated

Here are a few examples of how the string would look (as you can see, the order of the number changes) - note that there will only be one string at a time!

1)

$list = 'item[]=1&item[]=3&item[]=2&item[]=4';

2)

$list = 'item[]=3&item[]=1&item[]=4&item[]=2';

3)

$list = 'item[]=4&item[]=3&item[]=2&item[]=1';

This is how far I've got:

// check item[]= is repeated four times
if(substr_count($list, "item[]=") == '4') {

   // strip the string to only numbers, then will need to check each number if between 1-4
   $numbers = preg_replace("/[^0-9]/","",$list);

   // strip the string to only numbers and the character after it, will need to ensure it is & (except for the last number)
   preg_replace("/[^0-9]/","",$list + 1);

}

Solution

  • You can use:

    $list    = 'item[]=1&item[]=3&item[]=2&item[]=4';
    $pattern = "/^(item\[\]=[1-4])(&(item\[\]=[1-4])){3}$/";
    
    if (preg_match($pattern, $list)) {
        // check for repetition
        $matches = [];
        preg_match_all("/\d+/", $list, $matches);
    
        if (count(array_count_values($matches[0])) == 4) {
            // All are unique values
            echo 'All conditions met';
        }
    }