确保字符串遵循要求的格式 [英] Make sure that string follows the required format
本文介绍了确保字符串遵循要求的格式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试通过检查以下内容来检查字符串是否遵循某种格式:
I am attempting to check if a string follows a certain format by checking that:
-
item [] =
重复四次 -
item [] =
后跟一个数字和&
符号(例如item [] = 2&
),但最后一个除外数字后面没有&
-
item [] =
之后的数字仅由1-4组成,并且可以按任意顺序排列,但不能重复
item[]=
is repeated four timesitem[]=
is followed by a number and&
symbol (e.gitem[]=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';
这是我的目标:
// 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';
}
}
这篇关于确保字符串遵循要求的格式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文