douling8772 2013-11-07 22:35
浏览 94
已采纳

使用php从包含数值的字符串中删除前导零和尾随零

I'm trying to trim the leading and trailing zeros from a string that contains a numeric value used to represent a percentage.

I wrote this ugly block of code that combines rtrim(), ltrim() with a preg_replace():

rtrim(ltrim(preg_replace("/\d*\.(0(?![0$])|[1-9])*\K0+$/", "", $value),"0"), ".")

But it doesn't seem to work since if I enter 0010.003000 the output is 10.003000 instead of the desired 10.003

Is there a way to make a regex read right to left in Php (delete zeros from the right until you find a zero or a [1-9])? Or is there a way to improve my regex to accomplish my goal?

Important note: For some arguable reason I can't do a simple cast to float and simply enjoy the time saved playing videogames.

To better explain my strange question here are some samples with expected behaviors: 01.00 => 1 , 100 => 100 , 002.0050 => 2.005 , 0.005 => .005

  • 写回答

6条回答 默认 最新

  • douduoquan2824 2013-11-07 22:38
    关注

    Try the following:

    /^0+|\..+?\K0+$/g
    

    This either matches one or more 0s at the start-of-string ^0+, or it matches one or more 0s at the end-of-string 0+$.

    In PHP:

    preg_replace_all("/^0+|\..+?\K0+$/", "", $value)
    

    NOTE: I would recommend using the non regular expression solutions because they are more suitable for this simple situation. Nevertheless I posted this because you asked for a regular expression.

    Regex101 Demo

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(5条)

报告相同问题?

悬赏问题

  • ¥15 ubuntu22.04上安装ursim-3.15.8.106339遇到的问题
  • ¥15 求螺旋焊缝的图像处理
  • ¥15 blast算法(相关搜索:数据库)
  • ¥15 请问有人会紧聚焦相关的matlab知识嘛?
  • ¥15 网络通信安全解决方案
  • ¥50 yalmip+Gurobi
  • ¥20 win10修改放大文本以及缩放与布局后蓝屏无法正常进入桌面
  • ¥15 itunes恢复数据最后一步发生错误
  • ¥15 关于#windows#的问题:2024年5月15日的win11更新后资源管理器没有地址栏了顶部的地址栏和文件搜索都消失了
  • ¥100 H5网页如何调用微信扫一扫功能?