preg_replace正在取代$ signs

时间:2008-12-03 07:30:08

标签: php regex

我有以下代码片段将%POST_TITLE%等“模板标记”替换为名为$ post_title的变量的内容。

function replaceTags( $template, $newtext ) {
    $template = preg_replace( '/%MYTAG%/', $newtext, $template );
    return $template;
}

问题是,当$ post_full中包含'$'时,返回的结果会将其删除。例如:

$template = "Replace this: %MYTAG";
$newtext = "I earn $1,000,000 a year";

print replaceTags( $template, $newtext );

// RESULT
Replace this: I earn ,000,000 a year";

我知道这与没有正确转义$ newtext中的$ 1有关。我尝试过使用preg_quote()但它没有达到预期的效果。

2 个答案:

答案 0 :(得分:6)

嗯,既然你实际上没有使用正则表达式,为什么不使用str_replace呢?它会更快,你不会有像这样的奇怪问题。

答案 1 :(得分:3)

根据preg_replace manual,preg_replace()将此($1)视为 backreference
(而不是在preg_replace手册页的注释中提到的“回调语法”。
谢谢Jan Goyvaerts)。

$newtext = preg_replace("!" . '\x24' . "!" , '\\\$' , $newtext );

应该照顾你的'$'标志

相关问题