preg_replace正在取代$ signs

Car*_*arl 0 php regex

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

function replaceTags( $template, $newtext ) {
    $template = preg_replace( '/%MYTAG%/', $newtext, $template );
    return $template;
}
Run Code Online (Sandbox Code Playgroud)

问题是,当$ 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";
Run Code Online (Sandbox Code Playgroud)

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

der*_*ert 6

嗯,因为你实际上并没有在那里使用正则表达式,为什么不直接使用str_replace呢?它会更快,你不会有像这样的奇怪问题.