[英]how to remove trailing zeroes from a string not number php
I need to update table by removing trailing zeroes comes after a . 我需要通过删除结尾的零来更新表。 in a string.
在一个字符串中。 For example, consider the strings like
5x115.30
, 5x115.700
, 5x115.00
, 5-115.00
. 例如,考虑像琴弦
5x115.30
, 5x115.700
, 5x115.00
, 5-115.00
。 i know the floatval function. 我知道floatval函数。 But it not working for a string like this.
但是它不适用于这样的字符串。 Any ideas?
有任何想法吗?
preg_replace to rescue.... preg_replace进行救援...
<?php
$string1 = '5-115.000';
$string2 = '5.030x00115.7010';
$string1 = trim(preg_replace('#(\.[\d]*?)[0]+([\D]|$)#', '$1$2', $string1), '.');
$string2 = trim(preg_replace('#(\.[\d]*?)[0]+([\D]|$)#', '$1$2', $string2), '.');
print_r($string1);
print_r($string2);
Output : 输出:
5-115
5.03x00115.701
Regular Expression Explanation: 正则表达式说明:
\.[\d]*?)[0]+$
\. => this will ensure we only replace parts which starts with a . (dot)
[\d]*? => this means any digit such as 0-9, *? makes it optional (any amount of digit can be there or not, it doesn't matter to us)
[0]+ => here we are defining that we match literal 0 . + sign makes it to match multiple zeros
([\D]|$) => this group indicates either end of the string or any character other than numbers, so we only replace trailing zeros.
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.