如何将php7的preg_replace转换为preg_replace_回调

如何将php7的preg_replace转换为preg_replace_回调,php,preg-replace-callback,Php,Preg Replace Callback,我正在迁移一个php网站,并得到以下声明 “preg_replace():不再支持/e修饰符,请使用preg_replace_回调” 当更改为preg_replace_callback时,我收到一条错误消息“preg_replace_callback():需要参数2“$this->”(“\1”)才能成为有效的回调” 代码: 函数getFile($filename) { 如果($filename{0}='/'&&substr($this->fileRoot,-1)=='/')){ $filenam

我正在迁移一个php网站,并得到以下声明

“preg_replace():不再支持/e修饰符,请使用preg_replace_回调”

当更改为preg_replace_callback时,我收到一条错误消息“preg_replace_callback():需要参数2“$this->”(“\1”)才能成为有效的回调”

代码: 函数getFile($filename) { 如果($filename{0}='/'&&substr($this->fileRoot,-1)=='/')){ $filename=substr($filename,1); } $filename=$this->fileRoot.$filename; 如果(!($fh=@fopen($filename,'r')){ $this->err[]=PEAR::raiseError( $this->errorMessage(找不到它)。':“.$filename.”, 它没有找到 ); 返回“”; } $fsize=文件大小($filename); 如果($fsize<1){ fclose($fh); 返回“”; } $content=fread($fh,$fsize); fclose($fh); 返回预更换( “##输入法”, “\$this->$getFile('\\1')”, $content ); }//end func getFile
/**从preg\u replace更改为preg\u replace\u回调*/
返回preg_replace_回调(
“##输入法”,
“\$this->$getFile('\\1')”,
$content

提前感谢。

查看这段小代码,确保是preg\u replace\u callback()


首先当错误消息显示变量
$this->$getfile
在任何地方都不存在时。您必须查看这部分代码

Second根据您的代码和您对
$this
的使用,我们可以推断您的函数是
非静态方法
。因此在您的情况下,有效的
回调
可以是
对象的
数组
(作为第一项)和方法(作为第二项) 在您的情况下,
数组
应该是
[$this,“这里是您的方法的名称”]


查看以获取更多信息。

谢谢大家,我已经开始使用了。以下是更新的代码。return preg#u replace_callback(“###im”,函数($m){return$this->getFile($m[1])},$content
function getFile($filename)
{
    if ($filename{0} == '/' && substr($this->fileRoot, -1) == '/') {
        $filename = substr($filename, 1);
    }

    $filename = $this->fileRoot . $filename;

    if (!($fh = @fopen($filename, 'r'))) {
        $this->err[] = PEAR::raiseError(
            $this->errorMessage(IT_TPL_NOT_FOUND) . ': "' .$filename .'"',
            IT_TPL_NOT_FOUND
        );
        return "";
    }

    $fsize = filesize($filename);
    if ($fsize < 1) {
        fclose($fh);
        return '';
    }

    $content = fread($fh, $fsize);
    fclose($fh);

    return preg_replace(
        "#<!-- INCLUDE (.*) -->#ime",
        "\$this->$getFile('\\1')",
        $content
    );

} // end func getFile
    /** change from preg_replace to preg_replace_callback */
    return preg_replace_callback(
        "#<!-- INCLUDE (.*) -->#ime",
        "\$this->$getFile('\\1')",
        $content
 <?php
// this text was used in 2002
// we want to get this up to date for 2003
$text = "April fools day is 04/01/2002\n";
$text.= "Last christmas was 12/24/2001\n";
// the callback function
function next_year($matches)
{
  // as usual: $matches[0] is the complete match
  // $matches[1] the match for the first subpattern
  // enclosed in '(...)' and so on
  return $matches[1].($matches[2]+1);
}
echo preg_replace_callback(
            "|(\d{2}/\d{2}/)(\d{4})|",
            "next_year",
            $text);

?>