[英]how to remove trailing zeroes from a string not number php
我需要通過刪除結尾的零來更新表。 在一個字符串中。 例如,考慮像琴弦5x115.30
, 5x115.700
, 5x115.00
, 5-115.00
。 我知道floatval函數。 但是它不適用於這樣的字符串。 有任何想法嗎?
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.
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.