【问题标题】:Why preg_match_all forces me to provide the 3rd optional parameter? [closed]为什么 preg_match_all 强制我提供第三个可选参数? [关闭]
【发布时间】:2012-06-03 01:41:41
【问题描述】:

我正在使用preg_match_all 和这个正则表达式计算$text 中的一些特殊字符(如欧元符号)的数量:

preg_match_all('/[\[|\]|€\{|}|\\|\^|\||~]/u', $text);

出于某种奇怪的原因,PHP 要求我提供第三个参数。但根据documentation of preg_match_all,它应该是可选的:

警告:preg_match_all() 需要至少 3 个参数,给定 2 个。

如果我提供PREG_PATTERN_ORDER(甚至不知道我为什么要提供),我会得到:

无法通过引用传递参数 3。

那么,我的代码有什么问题?如果需要,这是整个函数:

public function getMessageCount($text)
{
    $specials   = preg_match_all('/[\[|\]|€\{|}|\\|\^|\||~]/u', $text)
    $characters = strlen($text) + $specials;

    if(in_array(strtolower($this->method), self::$classic_plans)) :

        if($characters >= 0   && $characters <= 160) return 1;
        if($characters >= 161 && $characters <= 306) return 2;
        if($characters >= 307 && $characters <= 459) return 3;
        if($characters >= 460 && $characters <= 612) return 4;

        return 5;

    endif;

    if(in_array(strtolower($this->method), self::$basic_plans)) :

        if($characters >= 0    && $characters <= 160)  return 1;
        if($characters >= 161  && $characters <= 312)  return 2;
        if($characters >= 313  && $characters <= 468)  return 3;
        if($characters >= 469  && $characters <= 624)  return 4;
        if($characters >= 625  && $characters <= 780)  return 5;
        if($characters >= 781  && $characters <= 936)  return 6;
        if($characters >= 937  && $characters <= 1092) return 7;
        if($characters >= 1093 && $characters <= 1248) return 8;

        return 9;

    endif;

    return in_array(strtolower($this->method), self::$zero_plans) ? 1 : null;
}

【问题讨论】:

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


    【解决方案1】:

    虽然第三个参数在 5.4.0 中成为可选的,就像其他人已经说过的那样,但是即使你传递了第三个参数,你的代码也不会编译,因为你说你传递了 PREG_PATTERN_ORDER 标志,但是第三个参数应该是接收匹配的数组并且第四个参数是标志。

    使用类似following:

    <?php
    $dummy = array();
    echo("Result = ".preg_match_all('/[\[|\]|x\{|}|\\|\^|\||~]/', $text, $dummy));
    ?>
    

    【讨论】:

      【解决方案2】:

      返回值preg_match_all 是一个int → 匹配数。匹配文本将填充到 3rd 参数中。

      // incorrect
      $specials = preg_match_all('/[\[|\]|€\{|}|\\|\^|\||~]/u', $text);      
      
      // correct
      $num = preg_match_all('/[\[|\]|€\{|}|\\|\^|\||~]/u', $text, $specials);
      

      【讨论】:

        【解决方案3】:

        从 PHP 5.4.0 开始,它成为可选的。

        更新日志

        5.4.0 匹配参数变为可选。

        【讨论】:

          【解决方案4】:

          查看您提供的链接中的更改日志。之后,检查您的 PHP 版本;)

          【讨论】:

          • 5.4.0 The matches parameter became optional.
          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2021-08-14
          • 1970-01-01
          • 1970-01-01
          • 2022-12-17
          • 1970-01-01
          • 2021-07-30
          相关资源
          最近更新 更多