Use a local variable in preg_replace_callback - PHP

ⅰ亾dé卋堺 提交于 2019-12-08 08:18:12

问题


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.


回答1:


The easiest way is with an anonymous callback:

$str = preg_replace_callback($regExp,function($match) use ($some_local_variable) {
    // do something
},$str);

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 &$some_var.

Of course, this requires PHP 5.3 or newer.



来源:https://stackoverflow.com/questions/15934249/use-a-local-variable-in-preg-replace-callback-php

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!