gpt4 book ai didi

php - 正则表达式替换小数

转载 作者:行者123 更新时间:2023-12-04 22:00:18 25 4
gpt4 key购买 nike

我正在尝试构建一个正则表达式来替换任何非以下格式的字符:

任意位数,然后可选(单个小数点,任意位数)

i.e.
123 // 123
123.123 // 123.123
123.123.123a // 123.123123
123a.123 // 123.123

我在 php 中使用 ereg_replace,最接近我管理的工作正则表达式是

ereg_replace("[^.0-9]+", "", $data);

这几乎是我需要的(除了它允许任意数量的小数点)

i.e.
123.123.123a // 123.123.123

我的下一次尝试是

ereg_replace("[^0-9]+([^.]?[^0-9]+)?", "", $data);

which was meant to translate as
[^0-9]+ // any number of digits, followed by
( // start of optional segment
[^.]? // decimal point (0 or 1 times) followed by
[^0-9]+ // any number of digits
) // end of optional segment
? // optional segment to occur 0 or 1 times

但这似乎只允许任意数量的数字,而不是其他任何东西。

请帮忙

谢谢

最佳答案

尝试以下步骤:

  1. 删除除 0-9 之外的任何字符。
  2. 删除第一个小数点后的任何.

这是一个使用正则表达式的实现:

$str = preg_replace('/[^0-9.]+/', '', $str);
$str = preg_replace('/^([0-9]*\.)(.*)/e', '"$1".str_replace(".", "", "$2")', $str);
$val = floatval($str);

还有一个只有一个正则表达式的:

$str = preg_replace('/[^0-9.]+/', '', $str);
if (($pos = strpos($str, '.')) !== false) {
$str = substr($str, 0, $pos+1).str_replace('.', '', substr($str, $pos+1));
}
$val = floatval($str);

关于php - 正则表达式替换小数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1142496/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com