Search code examples
phpregexpreg-replacecurrency

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


Solution

  • 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}');
    ?>