如何确保用户提交的数字输入遵循一定的格式


How to ensure user submitted numeric input follows a certain format

我在PHP工作,我想检查一个给定的用户提交的数字输入是不是太大或太小。

  • 我将数量存储在数据库中为64位整数(将它们乘以10^8以避免将来计算中的舍入错误)。我正在限制金额,以便它们不能超过以下精度:小数点后不超过4个数字。另外,由于用户输入的上限应该是9900万,我还想指定小数点前不超过8个数字。我怎样才能巧妙地做到这一点?

我现在的方法看起来有点像黑客:

代码:

//Check for existence of decimal point in string using strpos
//explode the string by the decimal point
//do a strlen on both the strings and check they dont exceed 8 and 4 respectively
//if no decimal point, simply do a strelen and check it's not greater than 8
  • 另外,我不希望输入的数据小于0.0001。我精通php网页设计,不熟悉php的数学函数,有一个简单的方法来处理这个?

谢谢你的建议

使用下面的代码可以检查$input是否符合您的要求。
(参见这个简短的演示)

$input = ...;
$pattern = "~^'s*'d{1,8}(?:'.'d{1,4})?'s*$~";
if (($input > 0) && preg_match($pattern, $input)) {
    /* $input is OK */
} else {
    /* $input is NOT OK */
}

要求:

  • $input的整数部分长度为1 ~ 8位。
  • $input可选包含.,后跟1到4位数字(小数部分)。
  • $input是一个大于等于0.0001的正数。

您可以使用正则表达式和mb_ereg_match(regex,string)函数

你可以试试:

if (preg_match('~^(?>[1-9]'d{0,7}+|0)(?>'.'d{0,3}+[1,9])?$~', trim($number), $result))
    // true
else
    // false

此模式避免了000151.000之类的事情,但如果您想允许这样做,只需将[1-9]替换为'd或更好地使用~^'d{1,8}+(?>'.'d{1,4}+)?$~

您必须在$result之后工作,其中包含修剪和验证的数字。

我认为下面的正则表达式将符合您的需求。

它将匹配99999999.9999到00000000.0000之间的所有带小数点和不带小数点的数字,以及空字符串。

分形部分不超过4位

if (preg_match('~^[0..9]{0,8}(?:'.[0..9]{1,4})?$~'), $number) {
  $match = TRUE;
} else{
  $match = FALSE;
}

看看是否有效:

$number = '123.4567';
if(preg_match('/^'s*'d*'.?'d{4}'s*$/', $number)) echo "Match";
else echo "Not match";