dswmmvrg40957 2019-06-21 09:33
浏览 158

比较php中的两个价格字符串与正则表达式

Say we have two price strings in different format:

$s_price = '85.95' or '1500.00'
$r_price = '$ 85.95' or '1,500'

But all these prices are the same and should match.

I have a regex to do that but don't know if this is how we do it:

(\d+)*(,)?\d+(.)?\d*
  • 写回答

3条回答 默认 最新

  • dongtun1683 2019-06-21 09:35
    关注

    To retrieve and parse a float from a string in PHP, use the floatval() method.

    For the symbols, it depends on wether you always use the same conventions for your currencies (comma for thousands separator and dot for decimals). In that case, you should remove non-digits except dots with the preg_replace() method (the correspondig Regex could be /[^0-9.]/)

    <?php
    
    function sanitize($price) {
        return floatval(preg_replace('/[^0-9.]/', '', $price));
    }
    
    $a1 = '85.95';
    $a2 = '1500.00';
    $b1 = '$ 85.95';
    $b2 = '1,500';
    
    sanitize($a1); // (float) 85.95
    sanitize($a2); // (float) 1500
    sanitize($b1); // (float) 85.95
    sanitize($b2); // (float) 1500
    
    sanitize($a1) === sanitize($b1); // (bool) true
    sanitize($a2) === sanitize($b2); // (bool) true
    sanitize($a1) <= sanitize($a2); // (bool) true
    sanitize($b1) >= sanitize($b2); // (bool) false
    

    Hope it will help !

    评论

报告相同问题?

悬赏问题

  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 对于相关问题的求解与代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 信号傅里叶变换在matlab上遇到的小问题请求帮助
  • ¥15 保护模式-系统加载-段寄存器
  • ¥15 电脑桌面设定一个区域禁止鼠标操作
  • ¥15 求NPF226060磁芯的详细资料
  • ¥15 使用R语言marginaleffects包进行边际效应图绘制