Link to home
Start Free TrialLog in
Avatar of rivusglobal
rivusglobalFlag for Canada

asked on

preg_replace - replace text contains "$0.32" and "dollar 0" is interpreted as the matching text!

Considering the following example, how can I get preg_replace to ignore the function of the replacement parameter that is introduced by the replacement text?

$text = "This item costs $0.99";
$html = "<b>%COST%</b>";

$html = preg_replace( "%COST%", $text, $html );

---------- the above produces the string below:

$html = "<b>This item costs %COST%.99</b>";

---------- but i want the previous code to produce this:

$html = "<b>This item costs $0.99</b>";

How can I do this?
Avatar of Roonaan
Flag of Netherlands image

$text = 'This item costs $0.99';
$html = '<b>%COST%</b>';

$html = str_replace('%COST%, $text, $html);

Alternatively you can use:

$html = stri_replace('%COST%', $text, $html);


$html = preg_replace('/%COST%/i', $text, $html);

Avatar of rivusglobal


Hi Roonaan,

I see that using str_replace doesn't have the $0 $1 $2 elements that a regular expression captures and that this is the WORKAROUND to the problem.  However, I'm using a preg_replace() function and in your second comment you use it as well but it fails in your example producing:

<b>%COST%This item costs .99</b>

As my $text string is created by the user, I see that it is dangerous and impossible to avoid this problem when using preg_replace().  Please tell me I'm wrong and there is in fact a way around this.

PS.  Thanks for your comment thus far.
Avatar of Roonaan
Flag of Netherlands image

Link to home
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Yeah that's the solution.  Coming from a perl background for using regular expressions, this open ended functionality seems rather insecure to me.

Thanks Roonaan for helping me figure it out, lol.