检测字符串中的整数值,更改它并将其保留在字符串中的同一位置

Detect integer value inside a string, alter it and leave it in the same place within the string

假设我们有一个看起来像这样的字符串:

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 结尾,trim 为零并将更改后的整数值留在内部的同一位置字符串。

最快的方法:

$str = '10.000 some text 5.200 some text 5.290 some text';
echo str_replace('0 ',' ', $str);
$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