假設我們有一個看起來像這樣的字串:
10.000 some text 5.200 some text 5.290 some text
我想要做的是從給定字串中的所有當前 int 值中洗掉最后一個零(如果存在),結果應該是:
10.00 some text 5.20 some text 5.29 some text
有沒有方便的方法呢?字串通常比給出的示例更復雜,因此我正在尋找一種方法來檢測整數值,檢查它是否以 0 結尾,修剪該零并將更改后的整數值留在字串內的同一位置。
uj5u.com熱心網友回復:
$text = '10.000 some text 5.200 some text 5.290 some text';
$result = preg_replace('(0(?=[^0-9.]))', '', $text);
echo $result; // Output: 10.00 some text 5.20 some text 5.29 some text
正則運算式模式詳細資訊:
( Start capturing group
0 Capturing group must start with a 0
(?= Start positive lookahead (meaning peek to the next character in the text)
[^0-9.] Make sure that the next character is not a digit or a dot
) End positive lookahead
) End capturing group
uj5u.com熱心網友回復:
最快的方法:
$str = '10.000 some text 5.200 some text 5.290 some text';
echo str_replace('0 ',' ', $str);
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/454228.html
上一篇:具有多個字符的C#子字串
