dpmfur2635 2014-03-20 10:27
浏览 73
已采纳

从preg_replace到preg_replace_callback

Hello fellow netheads!

I'm having issues with updating some old function to preg_replace_callback. Edit: what am I doing wrong?

This is my first (preg_replace/deprecated) function:

if ($handle) {
while (!feof($handle)) {
    $buffer = fgets($handle, 4096);
    @eval('$templ = new '.TEMPL_CLASS.';');
    $buffer = preg_replace("#§([a-z0-9-_]+)\.?([a-z0-9-_]+)?#ie","\$templ->\\1(\\2)",$buffer);
    $out .= $buffer;
    }
fclose($handle);
}

Second function (this is my attempt at converting to preg_replace_callback):

if ($handle) {
  while (!feof($handle)) {
    $buffer = fgets($handle, 4096);
    @eval('$templ = new '.TEMPL_CLASS.';');  
    $buffer = preg_replace_callback(
      '#§([\w-]+)\.?([\w-]+)?#',
      function ($m) {
        @$templ->$m[1]($m[2]);   
      },
      $buffer
    );
    $out .= $buffer;
  }
  fclose($handle);
}

OLD! M42's answear fixed the follow error:

Warning: preg_replace_callback(): Modifier /e cannot be used with replacement callback in /var/www/inc/engine.php on line 52

); <-- line 52
$out .= $buffer;

Edit: I dont know how to handle the render part of this..

$buffer = preg_replace("#§([a-z0-9-_]+)\.?([a-z0-9-_]+)?#ie","\$templ->\\1(\\2)",$buffer);

Right now it is rendering a blank page.. I guess the error is in

return templ($m[1], $m[2]);

  • 写回答

1条回答 默认 最新

  • dongzhan1948 2014-03-20 12:24
    关注

    As it's said in the message, removed the e modifier:

    '#§\\(\\[a-z0-9-_\\]+\\)\.?\\(\\[a-z0-9-_\\]+\\)?#i'
    //                                         here ___^
    

    And there're no needs to escape all these characters:

    '#§([a-z0-9_-]+)\.?([a-z0-9_-]+)?#i'
    

    [a-z0-9_] can be rewritten \w and there're no needs to i modifier

    '#§([\w-]+)\.?([\w-]+)?#'
    

    The whole instruction becomes:

    $buffer = preg_replace_callback(
      '#§([\w-]+)\.?([\w-]+)?#',
      function ($m) {
        return templ($m[1], $m[2]);
      },
      $buffer
    );
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 做个有关计算的小程序
  • ¥15 MPI读取tif文件无法正常给各进程分配路径
  • ¥15 如何用MATLAB实现以下三个公式(有相互嵌套)
  • ¥30 关于#算法#的问题:运用EViews第九版本进行一系列计量经济学的时间数列数据回归分析预测问题 求各位帮我解答一下
  • ¥15 setInterval 页面闪烁,怎么解决
  • ¥15 如何让企业微信机器人实现消息汇总整合
  • ¥50 关于#ui#的问题:做yolov8的ui界面出现的问题
  • ¥15 如何用Python爬取各高校教师公开的教育和工作经历
  • ¥15 TLE9879QXA40 电机驱动
  • ¥20 对于工程问题的非线性数学模型进行线性化