dream3323 2014-04-30 01:07
浏览 138
已采纳

多个字符串替换

All I want is to transform '1.234,56' into '1,234.56'...

I read about using array(s) as str_replace parameter, so I did this:

$value = '1.234,56';
$replacer1 = ',';
$replacer2 = '.';
echo \str_replace(array($replacer1, $replacer2), array($replacer2,$replacer1), $value);
//Prints '1,234,56' instead of '1,234.56'

The input and it's replacers are variable and it's not necessarily'll be used only for numbers.

Any ideas? Thanks...

  • 写回答

1条回答 默认 最新

  • dongyun51582 2014-04-30 01:31
    关注

    Try this.i used number_format() for this

    <?php
    
    $number = "1.234,56";
    
    $number = str_replace(array('.',','), array('','.'), $number);
    
    echo number_format($number, 2, '.', ',');
    

    You can also use money_format() function.Note that it won't work on windows.

    Here is another method.

    <?php
    
    $str = "1.234,56";
    
    $rp1 = '.';
    $rp2 = ',';
    
    //you might want to create a function for this.
    if(false===strpos($str, '@')){
    
    $str = str_replace($rp1, '@', $str);
    $str = str_replace($rp2, $rp1, $str);
    $str = str_replace('@', $rp2, $str);
    
    }
    
    echo $str;
    

    You can also use a unique string like #!MYSEP!#

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

报告相同问题?

悬赏问题

  • ¥15 Labview机器人问题
  • ¥15 Matlab编程问题
  • ¥15 训练的多模态特征融合模型准确度很低怎么办
  • ¥15 kylin启动报错log4j类冲突
  • ¥15 超声波模块测距控制点灯,灯的闪烁很不稳定,经过调试发现测的距离偏大
  • ¥15 import arcpy出现importing _arcgisscripting 找不到相关程序
  • ¥15 onvif+openssl,vs2022编译openssl64
  • ¥15 iOS 自定义输入法-第三方输入法
  • ¥15 很想要一个很好的答案或提示
  • ¥15 扫描项目中发现AndroidOS.Agent、Android/SmsThief.LI!tr