【问题标题】:Why is my preg_match_all not working?为什么我的 preg_match_all 不起作用?
【发布时间】:2017-03-09 07:39:46
【问题描述】:

我使用preg_match_all 来确保字符串遵循特定模式。

它应该显示“满足所有条件”,因为字符串遵循模式,而是显示“满足条件”。

$order = "item[]=2&item[]=1&item[]=3&item[]=4&item[]=5&item[]=6&item[]=7&item[]=8&item[]=9&item[]=10&item[]=11&item[]=12";
$pattern = "/^(item\[\]=([1-9]|10|11|12))(&(item\[\]=([1-9]|10|11|12))){11}$/";

if(preg_match($pattern, $order)) {

   // check for repetition
   $matches = [];
   preg_match_all("/\d+/", $order, $matches);
   if(count(array_count_values($matches[0])) == 12) {
      // All are unique values
      echo 'All conditions met';
   }
}else{
   echo 'Conditions not met';
}

【问题讨论】:

  • 您的$pattern 正则表达式不完整,您发布了您正在使用的那个吗?
  • 您的输入字符串看起来像一个查询字符串。我会使用parse_str() 将值放入数组中,然后检查数组的约束。这要容易得多。
  • 这是stackoverflow.com/questions/42679522/… 的类似故事,@AbraCadaver 提供了解决方案。你应该学习和使用parse_str函数
  • @axiac 我想你是对的。我来看看这个函数。
  • @RomanPerekhrest 很遗憾,因为他后来删除了他的答案。

标签: php preg-match preg-match-all


【解决方案1】:

正确的方法是使用
parse_str(解析查询字符串:键/值对用&分隔)
array_diff(检查是否所有所需范围1-12 中的数字存在且不重复)功能:

$order = "item[]=2&item[]=1&item[]=3&item[]=4&item[]=5&item[]=6&item[]=7&item[]=8&item[]=9&item[]=10&item[]=11&item[]=12";
parse_str($order, $items);

if (isset($items['item']) && is_array($items['item'])
    && count($items['item']) == 12 && !array_diff(range(1, 12), $items['item'])) {
    echo 'All conditions met';
} else {
    echo 'Conditions not met';
}

【讨论】:

  • 我应该也将这个答案发布到stackoverflow.com/questions/42679522/… 还是您愿意?
  • @TheCodesee,我认为这不是必需的,但您可以在每个问题中指定“相关”以使这些问题联系起来。喜欢交联
【解决方案2】:

试试这个:

<?php

$order = "item[]=2&item[]=1&item[]=3&item[]=4&item[]=5&item[]=6&item[]=7&item[]=8&item[]=9&item[]=10&item[]=11&item[]=12";
$pattern = "/^(item\[\]=([1-9]|10|11|12))(&(item\[\]=([1-9]|10|11|12))){11}$/";

if(preg_match($pattern, $order)) {

   // check for repetition
   $matches = [];
   preg_match_all("/\d+/", $order, $matches);
   if(count(array_count_values($matches[0])) == $movienumber) {
       // All are unique values
       echo 'All conditions met';
    }
}else{
   echo 'Conditions not met';
}

您在模式中缺少)

【讨论】:

  • 对不起,当我在这里发布代码时,这只是一个错误 - ) 在那里,我会更新我的问题。
【解决方案3】:

假设输入字符串在item[] 中包含从112 的所有值时是有效的(所有条件都满足),那么这段简单的代码比preg_match() 运行得更快并且更容易理解:

// Input string
$order = "item[]=2&item[]=1&item[]=3&item[]=4&item[]=5&item[]=6&item[]=7&item[]=8&item[]=9&item[]=10&item[]=11&item[]=12";

// Parse it to values and store them in $pieces
$pieces = array();
parse_str($order, $pieces);

// Need to sort the values to let the comparison succeed
sort($pieces['item']);
$valid = ($pieces['item'] == range(1, 12));

// Verification
var_dump($valid);
// It prints:
// bool(true)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-10-19
    • 1970-01-01
    • 2015-09-25
    • 2018-03-05
    • 2013-04-19
    • 2015-10-17
    • 2016-02-20
    • 2023-04-03
    相关资源
    最近更新 更多