chirag dodia
chirag dodia

Reputation: 525

How to keep digit and special character in preg_replace

I want to replace {goal} braces with a price such as $45. for example

 $pattern = /\{goal\}/

 $replacement = $45.00

 $subject = Final price is {goal}

so the function looks like

 preg_replace('/\\{goal\\}/', '$45.00', 'Free shipping for all orders over {goal}');

Actual output should be

Final price is $45.00

But I'm getting the output as

 Final price is .00

So it seems preg_replace replacing the whole digit and the special character with a blank string. Is there any solution to keep it.

Upvotes: 1

Views: 82

Answers (1)

Mohammad
Mohammad

Reputation: 21489

The $n will be replaced by the text captured by the n'th parenthesized pattern. manual

When you used '$45.00' php consider it as 45th captured group. So you should escape $ by \ to solving problem

preg_replace('/\{goal\}/', '\$45.00', 'Free shipping for all orders over {goal}');

Upvotes: 2

Related Questions