我正在尝试构建一个正则表达式来替换任何不符合格式的字符:
任意数量的数字,然后是可选的(单个小数点,任意位数)
i.e.
123 // 123
123.123 // 123.123
123.123.123a // 123.123123
123a.123 // 123.123
Run Code Online (Sandbox Code Playgroud)
我在php中使用ereg_replace,并且最接近我管理的工作正则表达式
ereg_replace("[^.0-9]+", "", $data);
Run Code Online (Sandbox Code Playgroud)
这几乎是我需要的(除了它将允许任意数量的小数点)
i.e.
123.123.123a // 123.123.123
Run Code Online (Sandbox Code Playgroud)
我的下一次尝试是
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
Run Code Online (Sandbox Code Playgroud)
但这似乎只允许任意数量的数字而没有别的.
请帮忙
谢谢
请尝试以下步骤:
0-9和之外的任何字符..第一个小数点后面的任何内容.这是一个使用正则表达式的实现:
$str = preg_replace('/[^0-9.]+/', '', $str);
$str = preg_replace('/^([0-9]*\.)(.*)/e', '"$1".str_replace(".", "", "$2")', $str);
$val = floatval($str);
Run Code Online (Sandbox Code Playgroud)
而另一个只有一个正则表达式:
$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);
Run Code Online (Sandbox Code Playgroud)