【问题标题】:preg_replace is replacing $ signspreg_replace 正在替换 $ 符号
【发布时间】:2008-12-03 07:30:07
【问题描述】:

我有以下代码,它将“模板标记”(例如 %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() 但它没有达到预期的效果。

【问题讨论】:

    标签: php regex


    【解决方案1】:

    嗯,既然你实际上并没有在那里使用正则表达式,为什么不直接使用str_replace?它会更快,而且你不会遇到这样的奇怪问题。

    【讨论】:

    • 好点。这是一个 wordpress 插件附带的代码,所以我什至没有想过要更改它。
    【解决方案2】:

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

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

    应该注意你的“$”符号

    【讨论】:

    • 为了准确起见,我决定给这个“答案”打勾,尽管 derobert 的答案也很准确。顺便说一句,什么是“!” . '\x24' 。 “!”位?
    • 其实我不确定!我想它会强制正则表达式仅匹配“$”符号(十六进制 ASCII 码为 24),但我不熟悉那个“!\x24!”正则表达式...
    • 您的解决方案是正确的,但您的术语是错误的。 $1 是反向引用,而不是回调。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-03-24
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多