简体   繁体   English

使用PHP在十进制前后删除零

[英]Remove zero after and before Decimal Using php

Below code works fine but in second variable name fixed_2 why it shows 3 digit after decimal? 下面的代码工作正常,但是在第二个变量名称为fixed_2的情况下,为什么小数点后显示3位数字? I tried many ways didn't get any hope. 我尝试了许多没有希望的方法。

$text = "000892021.2408000";

$fixed_1 = preg_replace('/000/','',$text);
$fixed_2 = preg_replace('/.000/','',$text);
$fixed_3 = preg_replace('/000./','',$text);

var_dump($fixed_1);
var_dump($fixed_2);
var_dump($fixed_3);

output 产量

 string(11) "892021.2408" string(13) "000892021.240" string(13) "92021.2408000" 

Any help please explain? 有什么帮助请解释?

您可以使用嵌套的ltrim()rtrim()

    $res = ltrim(rtrim($text, '0'), '0');

Well the regular expression you used for $fixed_2 is ".000" . 那么,您用于$ fixed_2的正则表达式为“ .000” It means remove all strings that start with any character followed by 3 zeros. 这意味着删除所有以任何字符开头,后跟3个零的字符串。 "." “” means any character, so it will match "8000" and will remove it. 表示任何字符,因此它将匹配“ 8000”并将其删除。 Thats why you got output of "000892021.240" in $fixed_2 这就是为什么您在$ fixed_2中获得“ 000892021.240”的输出的原因

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM