dongming4994 2018-01-30 19:15
浏览 70
已采纳

Preg_replace问题是剥离数字/字符长度?

Consider the following example....

The issue is with the preg_replace which is used to replace the variables total_balance_overriden and total_balance.

$text = 'this: {{total_balance_overridden}} - that: {{total_balance}}';

$total = '$517.50';
$overiddentotal = '$390.00';

$text = preg_replace('/{{total_balance_overridden}}/', $overiddentotal, $text);
$text = preg_replace('/{{total_balance}}/', $total, $text);


    echo $total;

    echo $overiddentotal;

    echo $text;

This gives me...

$517.50

$390.00

this: 0.00 - that: 7.50

It appears that the $total and $overiddentotal vars have the correct output, but when they have been replaced using the preg_replace, their length has been stripped, and the currency sign and first two numbers are missing. Any ideas why?

Note: If i replace the dollar sign with a pound sign it works! I get...

this: £390.00 - that: £517.50

So is the dollar sign and 2 numbers some sort of special character or var thats getting stripped?

  • 写回答

1条回答 默认 最新

  • douweihui0178 2018-01-30 19:28
    关注

    Dollar signs are special characters in replacement strings, they normally refer to captured substrings from the match. If you want a literal dollar sign, you have to escape it:

    $total = '\$517.50';
    $overiddentotal = '\$390.00';
    

    Note also, in this case, there's no need for regex at all. Just use str_replace() and you won't have this issue.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥20 sub地址DHCP问题
  • ¥15 delta降尺度计算的一些细节,有偿
  • ¥15 Arduino红外遥控代码有问题
  • ¥15 数值计算离散正交多项式
  • ¥30 数值计算均差系数编程
  • ¥15 redis-full-check比较 两个集群的数据出错
  • ¥15 Matlab编程问题
  • ¥15 训练的多模态特征融合模型准确度很低怎么办
  • ¥15 kylin启动报错log4j类冲突
  • ¥15 超声波模块测距控制点灯,灯的闪烁很不稳定,经过调试发现测的距离偏大