简体   繁体   English

如何验证PHP中的无符号数?

[英]How can I validate an unsigned number in PHP?

I'm not sure how to handle this one, and I've tried what to me are the most obvious solutions, but so far none have proved entirely satisfactory. 我不知道如何处理这个,我已经尝试过对我来说最明显的解决方案,但到目前为止还没有一个证明完全令人满意。 I must be overlooking something very simple. 我必须忽略一些非常简单的事情。

I have a form with an input of type text: 我有一个带有文本类型输入的表单:

<input type="text" name="album_id">

I want to validate the input so the users only enters unsigned integer... 我想验证输入,以便用户只输入无符号整数...

$required = array(); // required or invalid input

$tmp = trim($_POST['album_id']);

if (!is_int((int)$tmp)) {
   $required['album'] = 'The album id must contain a positive numeric value only.';
}

So far I've use !is_numeric($tmp) but a user can enter 9.2 or '1e4' and it will validate... so that one doesn't work. 到目前为止,我已经使用了!is_numeric($tmp)但是用户可以输入9.2或“1e4”,它将验证...以便一个不起作用。

I've also tried !is_int((int)$tmp) but for some reason, that one doesn't work (maybe it should but i'm doing it wrong...). 我也尝试过!is_int((int)$tmp)但由于某种原因,那个不起作用(也许它应该但我做错了......)。 I tried ctype_digit with no success. 我试过ctype_digit没有成功。 I'm probably overlooking something but not sure what. 我可能忽略了一些但不确定是什么。

How can I validate an unsigned number in php? 如何在php中验证无符号数? No floats, negative numbers, etc... only a simple unsigned number (1 to n). 没有浮点数,负数等...只有一个简单的无符号数(1到n)。

If you want to check if some variable only contains digits (which seems to be what you want, here) , you'll probably have to go with ctype_digit() . 如果你想检查一些变量是否只包含数字(这似乎是你想要的,这里) ,你可能需要使用ctype_digit()


Not sure what you tried, but something like this should work : 不确定你尝试了什么,但这样的事情应该有效:

$tmp = trim($_POST['album_id']);
if (ctype_digit($tmp)) {
    // $tmp only contains digits
}

The filter_var() function is the right tool for the job here. filter_var()函数是此处作业的正确工具。

Here's a filter that will return non-false only for unsigned integers or unsigned integer strings: 这是一个只对无符号整数或无符号整数字符串返回非假的过滤器:

$filteredVal = filter_var($inputVal, 
                          FILTER_VALIDATE_INT, 
                          array('options' => array('min_range' => 0)));

Here's the documentation on filters . 这是关于过滤器文档

Example: 例:

<?php

$testInput = array(
            "zero string" => "0",
            "zero" => 0,
            "int" => 111,
            "string decimal" => "222",
            "empty string" => "",
            "false" => false,
            "negative int" => -333,
            "negative string decimal" => "-444",
            "string octal" => "0555",
            "string hex" => "0x666", 
            "float" => 0.777,
            "string float" => "0.888",
            "string" => "nine"
         ); 

foreach ($testInput as $case => $inputVal)
{
    $filteredVal = filter_var($inputVal, 
                              FILTER_VALIDATE_INT, 
                              array('options' => array('min_range' => 0)));

    if (false === $filteredVal)
    {
        print "$case (". var_export($inputVal, true) . ") fails\n";
    } 
    else
    { 
        print "$case (". var_export($filteredVal, true) . ") passes\n";
    }
}

Output: 输出:

zero string (0) passes
zero (0) passes
int (111) passes
string decimal (222) passes
empty string ('') fails
false (false) fails
negative int (-333) fails
negative string decimal ('-444') fails
string octal ('0555') fails
string hex ('0x666') fails
float (0.777) fails
string float ('0.888') fails
string ('nine') fails

You could use preg_match() : 你可以使用preg_match()

if(preg_match('/^[\\d+]$/', $tmp) == 0)
    $required['album'] = 'The album id must ...';

Note that this won't do a positive range check (eg getting above the max valid value of an integer). 请注意,这不会进行正范围检查(例如,超过整数的最大有效值)。

Edit: Use Pascal MARTIN's solution unless you'd like to do more complex checks (eg requiring other special characters), as I'd guess it offers better performance for this use. 编辑:使用Pascal MARTIN的解决方案,除非你想做更复杂的检查(例如需要其他特殊字符),因为我猜它可以为这种用途提供更好的性能。

if (preg_match('!^[1-9][0-9]*$!',$tmp)) {

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM