Anil kumar
Anil kumar

Reputation: 4177

Preg_replace giving improper results when Currency Strings are given in Replace option

Preg_replace giving improper results when Currency Strings like ($1,500) are given in Replace option.

Here is my code

<?php
$amount = '$1,500.00';
echo $amount. "<br />";
echo preg_replace('/{amount_val}/', $amount, '{amount_val}'); // it gives ",500" but i need "$1,500"

?>

I tried with preg_quote, please have a look at following snippet

<?php

$amount = '$1,500.00';
$amount = preg_quote('$1,500.00');
echo $amount. "<br />";
echo preg_replace('/{amount_val}/', $amount, '{amount_val}'); // it gives "$1,500\.00" but i need "$1,500"

?>

How could i get exact result i.e. $1,500.00

Please help me in fixing this.

Thanks in advance

Upvotes: 0

Views: 161

Answers (2)

Jan
Jan

Reputation: 43169

Simply escape the dollar sign, see a demo on ideone.com:

<?php
$amount = '\$1,500.00';
echo preg_replace('~{amount_val}~', $amount, '{amount_val}');
// output: $1,500
?>

Alternatively (is this really what you're after ???)

<?php
$amount = '$1,500.00';
echo preg_replace('~{amount_val}~', str_replace('$', '\$', $amount), '{amount_val}');
?>

Upvotes: 1

Casimir et Hippolyte
Casimir et Hippolyte

Reputation: 89584

Since you want to replace a literal string, you don't need to use regex:

$amount = '$1,500.00';
$result = str_replace('{amount_val}', $amount, $yourstring);

Now why you obtain a strange result with preg_replace?

In the replacement string each sequence $n where n is a digit or a &, is seen as a reference to a capture group and is a place holder for the character captured in this group. That's why, to avoid ambiguities, you should escape the $ character to be sure to obtain a literal $.

Upvotes: 1

Related Questions