如何从字符串中删除尾随零而不是数字php

时间:2018-01-23 04:47:06

标签: php

我需要通过删除后面的尾随零来更新表。在一个字符串中。 例如,请考虑5x115.305x115.7005x115.005-115.00等字符串。 我知道floatval函数。但它不适合这样的字符串。有什么想法吗?

1 个答案:

答案 0 :(得分:0)

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);

输出:

5-115
5.03x00115.701

正则表达式说明:

\.[\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.