【发布时间】:2014-02-11 14:04:24
【问题描述】:
我正在尝试使用preg_replace_callback 根据this answer 在导入的文档(由我控制)中填写变量,但它不起作用。据我所知,回调永远不会被调用,这意味着正则表达式永远不会被匹配。
doc.html 文件的基本内容:
<p>test {$test} $test test</p>
PHP:
$test = "ham";
$allVars = get_defined_vars();
$filename = "/path/to/doc.html";
$html = file_get_contents($filename);
$html = preg_replace_callback("/\$[a-zA-Z_][a-zA-Z0-9_]*/", "find_replacements", $html);
echo($html);
exit();
// replace callback function
function find_replacements($match) {
global $allVars;
if (array_key_exists($match[0], $allVars))
return $allVars[$match[0]];
else
return $match[0];
}
输出是<p>test {$test} $test test</p>,但我期待的是<p>test {ham} ham test</p>
【问题讨论】:
-
我不会使用
$,因为 PHP 已经将它用于插值,它可能会导致严重的错误。尝试使用其他字符,例如test {#test} #test test -
如果您使用
$,也请尝试将您的正则表达式放在单引号中。 -
就是这样——在我的正则表达式周围使用单引号。你能写一个答案来解释原因吗?
-
讨厌的错误!下面的答案很好,但我的解决方案是选择一个不同的角色。
标签: php regex preg-replace-callback