【问题标题】:Make sure that string follows the required format确保字符串遵循所需的格式
【发布时间】:2017-03-08 18:48:06
【问题描述】:

我试图通过检查来检查字符串是否遵循某种格式:

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

}

【问题讨论】:

  • 所以你今天早些时候提出这个问题时完全忽略了我的建议?
  • @MarkBaker 嗨,马克,我确实指出,在您发表评论后,我意识到我错过了我的问题中的一些标准。
  • 而且你不熟悉 PHP 的 max() 和 min() 函数:parse_str($list, $output); if (isset($output['item']) && count($output['item']) == 4 && count(array_unique($output['item'])) == 4 && min($output['item']) == 1 && max($output['item']) == 4) { echo 'All OK!'; }

标签: php arrays preg-replace substr


【解决方案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';
    }
}

【讨论】:

  • 1-4,可以任意顺序,但不能重复
  • 你好,好像收到了这个错误preg_match_all(): Delimiter must not be alphanumeric or backslash -- at line 9
  • @TheCodesee 抱歉,忘记包含/。更新答案
  • @Jomoos 没关系,但您的代码未显示“满足所有条件”
  • @TheCodesee 更新
猜你喜欢
  • 2016-06-07
  • 1970-01-01
  • 2022-01-17
  • 2019-02-14
  • 2019-03-03
  • 1970-01-01
  • 2021-07-05
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多