2008-12-03 62 views
0

我有以下一段代码,它将名为“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(),但它没有达到预期的效果。

回答

3

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

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

因为你实际上并没有使用正则表达式有,为什么不使用str_replace应该把你的“$”符号

+0

为了准确,我决定给这个“答案”打勾,虽然derobert的回答也相当准确。顺便说一句,什么是“!” 。 '\ x24'。 “!”位? – Carl 2008-12-03 07:53:57

+0

我不确定!我想它强制正则表达式只匹配'$'符号(这是十六进制ASCII代码中的24),但我不熟悉那个“!\ x24!”正则表达式... – VonC 2008-12-03 08:06:51

6

嗯照顾,?它会更快,你不会有这样的奇怪问题。