Avatar of rivusglobal
rivusglobal
Flag 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?
PHP

Avatar of undefined
Last Comment
rivusglobal

8/22/2022 - Mon
Roonaan

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

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

-r-
Roonaan

Alternatively you can use:

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

Or

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

-r-
rivusglobal

ASKER
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.
This is the best money I have ever spent. I cannot not tell you how many times these folks have saved my bacon. I learn so much from the contributors.
rwheeler23
ASKER CERTIFIED SOLUTION
Roonaan

Log in or sign up to see answer
Become an EE member today7-DAY FREE TRIAL
Members can start a 7-Day Free trial then enjoy unlimited access to the platform
Sign up - Free for 7 days
or
Learn why we charge membership fees
We get it - no one likes a content blocker. Take one extra minute and find out why we block content.
Not exactly the question you had in mind?
Sign up for an EE membership and get your own personalized solution. With an EE membership, you can ask unlimited troubleshooting, research, or opinion questions.
ask a question
rivusglobal

ASKER
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.