Make sure that string follows the required format

 ̄綄美尐妖づ 提交于 2020-01-17 06:08:10

问题


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);

}

回答1:


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


来源:https://stackoverflow.com/questions/42679522/make-sure-that-string-follows-the-required-format

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!