tags:

views:

146

answers:

2

I have the following piece of code which replaces "template markers" such as %POST_TITLE% with the contents of a variable called $post_title.

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

The issue is that when $post_full has a '$' in it, the returned result has this 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 something to do with not properly escaping the $1 in the $newtext. I have tried using preg_quote() but it doesn't have the desired effect.

+2  A: 

According to preg_replace manual, preg_replace() treats this ($1) as backreference.
(and not a "callback syntax" as mentionned in the comments of the preg_replace manual page.
Thank you Jan Goyvaerts).

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

should take care of your '$' sign

VonC
For accuracy, I've decided to give this the "answer" tick, although derobert's answer is also quite accurate. BTW, what is the "!" . '\x24' . "!" bit?
Carl
I am not sure actually! I suppose it forces the regex to match only '$' sign (which is 24 in hexadecimal ASCII code), but I am not familiar with that "!\x24!" regex...
VonC
Your solution is correct, but your terminology is wrong. $1 is a backreference, not a callback.
Jan Goyvaerts
+6  A: 

Ummm, since you aren't actually using a regexp there, why not just use str_replace? It'll be faster and you won't have weird issues like this.

derobert
Good point. It's code that came with a wordpress plugin so I never even thought of changing it.
Carl