Preg_replace在替换选项中给出货币字符串时给出不正确的结果


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

Preg_replace

替换选项中给出货币字符串(如($1,500)时给出不正确的结果。

这是我的代码

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

我尝试了preg_quote,请查看以下片段

<?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"
?>

我怎么能得到确切的结果,即 $1,500.00

请帮助我解决这个问题。

提前致谢

只需转义美元符号,请参阅 ideone.com 上的演示:

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

或者(这真的是你所追求的???)

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

由于您要替换文字字符串,因此不需要使用正则表达式:

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

现在为什么你会得到一个奇怪的结果preg_replace

在替换字符串中,每个序列$n其中 n 是数字或&,被视为对捕获组的引用,并且是该组中捕获字符的占位符。这就是为什么为了避免歧义,您应该转义$字符以确保获得文字$