确保字符串遵循所需的格式
Make sure that string follows the required format
我试图通过检查以下内容来检查字符串是否遵循特定格式:
item[]=
重复四次
item[]=
后跟一个数字和 &
符号(例如 item[]=2&
),除了最后一个数字后面没有 &
item[]=
后面的数字只能由1-4中的任意一个组成,可以任意排列,但不能重复
这里有几个字符串的外观示例(如您所见,数字的顺序会发生变化)- 请注意,一次只会有一个字符串!
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';
这是我的进度:
// 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);
}
您可以使用:
$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';
}
}
我试图通过检查以下内容来检查字符串是否遵循特定格式:
item[]=
重复四次item[]=
后跟一个数字和&
符号(例如item[]=2&
),除了最后一个数字后面没有&
item[]=
后面的数字只能由1-4中的任意一个组成,可以任意排列,但不能重复
这里有几个字符串的外观示例(如您所见,数字的顺序会发生变化)- 请注意,一次只会有一个字符串!
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';
这是我的进度:
// 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);
}
您可以使用:
$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';
}
}