保留数字和十进制格式,但删除其他所有内容


keep format of number and decimal but remove everything else

我有一个州税和地方税的输入字段。

输入每个字段的数据,然后将它们加在一起得到totaltax。

我试过number_format和round和print_f,但他们都没有工作,因为我需要他们。我想找到preg_match的可能性。

我需要的是,输入字段将是这样的:

10.2
10.33
10.301
3.275
2.90

如果有人输入0.10,它应该转换为0.10。如果他们输入0.10,它应该保持不变。同样的,0.125应该输入0.125

如果不是数字或小数,则需要删除

$statetax = $_POST['statetax']; 
$localtax = $_POST['localtax'];
$totaltax = $statetax+$localtax;
insert into tax (state, local, total) values($state, $local, $total)

谢谢!

这就是我最终使用的。

$statetax = preg_replace("/[^0-9'.]/", "",$_POST['statetax']);
$localtax = preg_replace("/[^0-9'.]/", "",$_POST['localtax']);
$totaltax = ($statetax+$localtax);

感谢大家的参与

您应该使用is_numeric()来确保您的输入是一个数字。然后转换为浮点数并返回到字符串,以确保在需要时准备0。这里使用floatval()strval()

我希望下面的例子有所帮助:

$tests = array(
    '10.2',
    '10.33',
    '.301',
    'bar',
    '3.275',
    '2.90',
    '.1',
    'foo'
);
foreach($tests as $input) {
    // check if the value is number using `is_numeric`
    if(!is_numeric($input)) {
        echo "Error: Not a number: $input'n";
        continue;
    }   
    // convert to float and back to string ( in the echo ) will 
    // automatically prepend a 0 if required
    $sanitizedInput = strval(floatval($input));
    echo "Sanitized input: $sanitizedInput'n";
}

尝试:

$statetax = (float) is_numeric($_POST['statetax']) ? $_POST['statetax'] : 0;
$localtax = (float) is_numeric($_POST['localtax']) ? $_POST['localtax'] : 0;
$totaltax = $statetax + $localtax;
mysql_query(
    "insert into tax ('state', 'local', 'total') values($statetax, $localtax, $totaltax)"
);

一般来说,在构建SQL字符串时转义用户输入($_POST,…)是个好主意。否则,您将自己设置为SQL注入。请在这里阅读。在这种情况下,没有必要这样做,因为float类型转换确保您的POST值被"转义"。

相关文章: