我正在尝试在 Internet 上部署我的网站,以便在真实环境中对其进行测试。它是某种文本编辑器,用户可以在其中使用正则表达式和用户定义的回调函数。
我对 preg_replace_callback() 函数有一些问题。我的主机的 PHP 版本早于 5.3,我不能在我的代码中使用匿名函数(我在 localhost 有 PHP 5.4)。所以我必须重写这部分代码(在本地主机上正常工作)
$newString = preg_replace_callback(
'#' . $this->pattern . '#' . $this->modifiers,
function($match)
{
return eval('return ' . $this->replacement . ';');
},
$string);
在这一点上,我不是在谈论使用 eval() 的危险——这个问题稍后会得到适当的注意(“禁止”单词列表检查等)。问题是我在下面的尝试
$replacement = $this->replacement;
$newString = preg_replace_callback(
'#' . $this->pattern . '#' . $this->modifiers,
create_function('$match', '
global $replacement;
return eval(\'return \' . $replacement . \';\');
'),
$string);
不起作用,也不会发生错误。我的代码有什么问题?
任何帮助将非常感激。
新信息。我试过这个
Class A
{
public function check()
{
$string = 'series 3-4';
$pattern = 'series[ ]*(\d+)[ ]*-[ ]*(\d+)';
$modifiers = 'um';
$replacement = '$match[2] == $match[1] + 1 ? "series $match[1] and $match[2]" : "series $match[1]-$match[2]"';
$newString = preg_replace_callback(
'#' . $pattern . '#' . $modifiers,
create_function('$match', '
global $replacement;
echo $replacement;
return eval(\'return \' . $replacement . \';\');
'),
$string);
echo $newString;
}
}
$a = new A;
$a->check();//get nothing
并发现 create_function() 中的 $replacement 是空的。但是当我在类之外使用相同的 create_function() 时,$replacement 不为空:
$string = 'series 3-4';
$pattern = 'series[ ]*(\d+)[ ]*-[ ]*(\d+)';
$modifiers = 'um';
$replacement = '$match[2] == $match[1] + 1 ? "series $match[1] and $match[2]" : "series $match[1]-$match[2]"';
$newString = preg_replace_callback(
'#' . $pattern . '#' . $modifiers,
create_function('$match', '
global $replacement;
echo $replacement . "<br/>";
return eval(\'return \' . $replacement . \';\');
'),
$string);
echo $newString;
//$match[2] == $match[1] + 1 ? "series $match[1] and $match[2]" : "series $match[1]-$match[2]"
//series 3 and 4