FROM preg_replace TO preg_replace_callback

ⅰ亾dé卋堺 提交于 2019-12-11 03:05:21

问题


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:


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
);


来源:https://stackoverflow.com/questions/22530027/from-preg-replace-to-preg-replace-callback

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