Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why preg_match_all forces me to provide the 3rd optional parameter? [closed]

I'm counting the number of some special characters (like euro symbol) in $text, using preg_match_all and this regular expression:

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

For some strange reason PHP asks me for a third parameter. But it's supposed to be optional as per documentation of preg_match_all:

Warning: preg_match_all() expects at least 3 parameters, 2 given.

If i provide PREG_PATTERN_ORDER (even don't know why should i) i get:

Cannot pass parameter 3 by reference.

So, what's wrong with my code? Here is the whole function if needed:

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;
}
like image 702
gremo Avatar asked Feb 20 '23 08:02

gremo


2 Answers

Although 3rd parameter became optional in 5.4.0 like others have said already but your code doesn't compile even if you pass 3rd parameter because you said you pass PREG_PATTERN_ORDER flag but 3rd parameter is supposed to be the array that receives matches and 4th parameter is flag.

Use something like the following:

<?php
$dummy = array();
echo("Result = ".preg_match_all('/[\[|\]|x\{|}|\\|\^|\||~]/', $text, $dummy));
?>
like image 183
Muhammad Hasan Khan Avatar answered Feb 23 '23 00:02

Muhammad Hasan Khan


It became optional from PHP 5.4.0.

Changelog

5.4.0 The matches parameter became optional.

like image 20
Jeroen Avatar answered Feb 22 '23 22:02

Jeroen