2008-12-03 61 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

嗯照顧,?它會更快,你不會有這樣的奇怪問題。