php数字 验证
数字
在处理数字时,如货币金额,实际上并没有通用的检验方式,而是要根据特定输入信息检查数据是否在有效范围之内。不过我们可以创建一个函数来标准化得到的任何数值,所使用的格式满足大多数数据库对数值格式的要求,也就是说数字之间没有空格或逗号,负数值前面会有一个负号。另外,利用可选参数指定保留的小数位,自动进行四舍五入的操作。
PHP能够根据需要自动把字符串转化为数值,但逗号、空格和其他一些因素经常会影响这种转化。程序清单11.4.1解决了这些问题,从而得到有效的数值。
程序清单11.4.1 通用数值检验函数库
<?php
// A function that will accept and clean up number strings
function standardize_number($num, $precision = false) {
// First, remove all non-digits, periods, and - signs from the string
$num = preg_replace('/[^-.0-9]/', '', $num);
// Now remove any -'s that are in the middle of the string:
$num = preg_replace('/(?<=.)-/', '', $num);
// We now have a valid string that PHP will properly consider a number.
// If a precision was asked for, round accordingly:
if ($precision !== false) {
$num = round($num, $precision);
}
return $num;
}
// Standardize some number strings:
$nums = array('123.4643', 'Hello I bought 42 flowers for you.',
'-344-345.424', '+544,342.566');
foreach ($nums as $num) {
$st = standardize_number($num, 2);
echo "<p>{$num} = {$st}</p>\n";
}
?>
|