有时您想验证应该是数字但输入的输入,$_GET
否则$_POST
您会将其作为字符串获取。is_numeric()
可能有问题,因为它允许十六进制、二进制和八进制格式(来自手册):
Thus +0123.45e6 is a valid numeric value. Hexadecimal (e.g. 0xf4c3b00c), Binary (e.g. 0b10100111001), Octal (e.g. 0777) notation is allowed too but only without sign, decimal and exponential part.
您不能使用is_int()
它,因为它仅用于整数值(不是字符串!)所以...您可以通过这种方式验证字符串和整数的数字:
/**
* Validate integer.
*/
class IntegerValidator
{
/**
* Run validation.
* @param string $value
* @return bool
*/
public static function isIntVal(string $value): bool
{
if (!self::hasValidIntegerFormat($value)) {
return false;
}
return !self::hasLeadingZero($value);
}
/**
* Check if given string looks like valid integer. Negative numbers allowed.
* @param string $value
* @return bool
*/
private static function hasValidIntegerFormat(string $value): bool
{
return (bool) preg_match('/^-?[0-9]+$/', $value);
}
/**
* Check if given number has leading 0. Thus it's invalid integer.
* @param string $number
* @return bool
*/
private static function hasLeadingZero(string $number): bool
{
return self::extractFirstDigit($number) === 0;
}
/**
* Extract first digit from given number.
* @param string $number
* @return int
*/
private static function extractFirstDigit(string $number): int
{
return self::isNegativeInteger($number)
? (int) $number[1]
: (int) $number[0];
}
/**
* Check if number is negative integer. ie. starts with minus sign on the beginning.
* @param string $number
* @return bool
*/
private static function isNegativeInteger(string $number): bool
{
return $number[0] === '-';
}
}
var_dump(IntegerValidator::isIntVal('123')); // true
var_dump(IntegerValidator::isIntVal('0123')); // false
var_dump(IntegerValidator::isIntVal('-0123')); // false
var_dump(IntegerValidator::isIntVal('-123')); // true
也可以使用override_function()覆盖 is_int() 函数,但它在原始版本中仍然可能有用。