在preg_replace_callback中使用局部变量 - PHP

san*_*a26 1 php preg-replace-callback

如何preg_replace_callback在PHP中使用局部变量.我有以下代码:

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); 
Run Code Online (Sandbox Code Playgroud)

而且也是$str一个字符串,$reg_exp是一个正则表达式.这两个都很明确.

谢谢你的帮助.

Nie*_*sol 7

最简单的方法是使用匿名回调:

$str = preg_replace_callback($regExp,function($match) use ($some_local_variable) {
    // do something
},$str);
Run Code Online (Sandbox Code Playgroud)

请注意,您可以通过这种方式添加多个变量,但是它会在定义函数时创建该变量的副本(如果您将其分配给变量以进行多次使用,这很重要).如果您想要变量的"实时"引用,请使用&$some_var.

当然,这需要PHP 5.3或更高版本.