4

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;
}
gremo
  • 47,186
  • 75
  • 257
  • 421

4 Answers4

4

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));
?>
Muhammad Hasan Khan
  • 34,648
  • 16
  • 88
  • 131
2

It became optional from PHP 5.4.0.

Changelog

5.4.0 The matches parameter became optional.

Community
  • 1
  • 1
Jeroen
  • 13,056
  • 4
  • 42
  • 63
1

Check out the changelog in the link you provided. After that, check your PHP version ;)

Mihai Todor
  • 8,014
  • 9
  • 49
  • 86
1

the return value preg_match_all is an int → number of matches. The matches text will be filled in the 3rd parameter.

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

// correct
$num = preg_match_all('/[\[|\]|€\{|}|\\|\^|\||~]/u', $text, $specials);
flowfree
  • 16,356
  • 12
  • 52
  • 76