并不完美,但它的工作
function priceToFloat($s){
// clear witespaces
$s = trim($s);
$s = str_replace(' ', '', $s);
// is it minus value
$is_minus = false;
if(strpos($s, '(') !== false)
$is_minus = true;
if(strpos($s, '-') !== false)
$is_minus = true;
// check case where string has "," and "."
$dot = strpos($s, '.');
$semi = strpos($s, ',');
if($dot !== false && $semi !== false){
// change fraction sign to #, we change it again later
$s = str_replace('#', '', $s);
if($dot < $semi) $s = str_replace(',','#', $s);
else $s = str_replace('.','#', $s);
// remove another ",", "." and change "#" to "."
$s = str_replace([',','.', '#'], ['','', '.'], $s);
}
$s = str_replace(',', '.', $s);
// clear usless elements
$s = preg_replace("/[^0-9\.]/", "", $s);
// if it minus value put the "-" sign
if($is_minus) $s = -$s;
return (float) $s;
}
工作情况
$prices = [
'123.456,789',
'123,456.789',
'123 456,789',
'123 456.789',
'-123,456.789',
'(123,456.789)',
];
foreach($prices as $price)
echo priceToFloat($price).'<br />';
回报
123456.789
123456.789
123456.789
123456.789
-123456.789
-123456.789
为什么没有正则表达式?这极大地限制了你... – Nick 2012-02-02 10:18:20
所以输入是可变的,即使点和零可能意味着数千分隔符或小数点..并且你认为这有一个魔术锤,对于你可能从用户那里得到的所有可能的输入? – 2012-02-02 10:18:47
@尼克我说“比较喜欢”,因为我认为正则表达式很难阅读和难以维护。但如果需要的话,我仍然会使用它们。 – PiTheNumber 2012-02-02 10:30:42