保持数字和小数的格式,但删除其他所有内容

时间:2013-04-23 23:11:50

标签: php numbers preg-match

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

输入每个字段数据然后我将两者一起添加以获得totaltax。

我尝试过number_format和round以及print_f,但是没有一个能像我需要的那样工作。我试图找到preg_match的可能性。

我需要的是,输入字段将采用如下内容:

10.2
10.33
10.301
3.275
2.90

如果有人输入.10,则应转换为0.10。如果他们输入0.10就应该不管它。相同的.125应输入为0.125

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

$statetax = $_POST['statetax']; 
$localtax = $_POST['localtax'];
$totaltax = $statetax+$localtax;

insert into tax (state, local, total) values($state, $local, $total)

谢谢!

3 个答案:

答案 0 :(得分:2)

这是我最终使用的。

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

感谢大家的欢呼声。

答案 1 :(得分:1)

您应该使用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";
}

答案 2 :(得分:0)

尝试:

$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注入做好准备。阅读here。在这种情况下,它不是必需的,因为浮动类型转换确保您的POST值被“转义”。

相关问题