Preg_replace replaces $ sign

I have the following piece of code that replaces "templated markers" like% POST_TITLE% with the contents of a variable named $ post_title.

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

      

The problem is, when $ post_full has '$' in it, the returned result is removed. For example:

$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";

      

I know this has to do with not being able to escape $ 1 in $ newtext. I tried using preg_quote () but it doesn't have the desired effect.

0


source to share


2 answers


According to preg_replace manual , preg_replace () sees this ( $1

) as the reverse link . (not the callback syntax
"as pointed out in the comments of the preg_replace man page.
Thanks to Jan Goywarts ).

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

      



should take care of your $$ sign

+3


source


Ummm, since you're not actually using regexp, why not just use str_replace

? It will be faster and you won't have such weird problems.



+6


source







All Articles