Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use a local variable in preg_replace_callback - PHP [duplicate]

How to use a local variable in preg_replace_callback in PHP. I have the following code:

function pregRep($matches)
{
    global $i; $i++;

    if($i > 2)
    {     
          return '#'.$matches[0];
    }
    else
    {
        return $matches[0];
    }
}

$i = 0;
$str =  preg_replace_callback($reg_exp,"pregRep",$str); 

And also $str is a string, $reg_exp is a regex expression. Both of these are well defined.

Thanks for your help.

like image 291
sanchitkhanna26 Avatar asked Jun 19 '26 15:06

sanchitkhanna26


1 Answers

The easiest way is with an anonymous function as callback:

$result = preg_replace_callback(
    $pattern,

    function ($match) use ($variable) {
        // do something
    },

    $subject
);

Note that you can add multiple variables in this way, but it will create a copy of that variable as it is when the function is defined (this is important if you are assigning it to a variable for multiple uses). If you want a "live" reference to the variable, use &$variable.

Of course, using arrow functions instead requires PHP 7.4 or newer.

like image 92
Niet the Dark Absol Avatar answered Jun 21 '26 05:06

Niet the Dark Absol



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!