PHP preg_replace - 如何在没有`/ e``eval`的情况下获得相同的结果 - 提高了安全性和速度性能?

时间:2011-07-20 20:11:57

标签: php regex security eval

如何在没有/e eval的情况下获得相同的结果 - 提高了安全性和速度性能?

function finclude($file){
    return include($file);
}

$str = "Today is {include 'date.php'}.";
echo preg_replace("/\{include '(.*)\'}/e", 'finclude("$1")', $str);

date.php:

<?php return date('jS \of F'); ?>, 2011

结果:Today is 20th of July.

3 个答案:

答案 0 :(得分:2)

您可以使用preg_replace_callback

echo preg_replace_callback("/\{include '(.*)\'}/", function($m) {
  return include($m[1]);
}, $str);

答案 1 :(得分:1)

您可以使用preg_replace_callback()

echo preg_replace_callback("/\{include '(.*)\'}/", function ($matches) {
    // TODO, here : some test on $matches[1], to make sure that including it is safe
    return include $matches[1];
}, $str);

答案 2 :(得分:0)

echo preg_replace_callback("/\{include '(.*)\'}/", function($matches){finclude($matches[1]);}, $str);