在 PHP 中将任何字符串数字转换为整数类型,考虑到 int 返回 0 表示失败而不是 false


Convert any string number into integer type in PHP considering toInt returns 0 for fail instead of false

如果

给定字符串为不是类型 [PHP INT] 的有效数字,否则返回 TRUE。

这在其他语言中很简单。

intval()、isint() 和 is_numeric() 是不够的,原因如下:

is_numeric() 是不够的,因为它匹配任何数字,不仅仅是整数,它还接受巨大的数字作为数字,这些数字不是整数。 intval() 是不够的,因为它为无效的 PHP 整数(如 '900000000000000000' 和

有效的 PHP 整数 '0' 或 '0x0' 或 '0000' 等返回 0。 isint() 只测试变量是否已经是 int 类型, 它不处理字符串或转换为 int。

也许有一个流行的库来做这个什么?

例如,我想调用一个能够检测某人发布的表单数据是否为有效 php 整数的函数。

我想调用执行此操作的函数:is_php_integer($str_test_input)。函数中有什么?

<?php
$strInput = 'test' //function should return FALSE
$strInput = '' //function should return FALSE
$strInput = '9000000000000000'  //function should return FALSE since
                            //is not valid int in php
$strInput = '9000' //function should return TRUE since
                    //valid integer in php
$strInput = '-9000' // function should return TRUE
$strInput = '0x1A' // function should return TRUE
                    // since 0x1A = 26, a valid integer in php
$strInput = '0' // function should return TRUE, since
                    // 0 is a valid integer in php
$strInput = '0x0' // function should return TRUE, since
                    // 0x0 = 0 which is a valid integer in php
$strInput = '0000' // function should return TRUE, since
                    // 0000 = 0 which is a valid integer in php
function is_php_integer($strTestInput) {
    // what goes here?
    // ...
    // if string could be interpreted as php integer, return true
    // else, return false
}
if is_php_integer($strInput) {
    echo 'your integer plus one equals: '. (intval($strInput) + 1);
} else {
    echo 'your input string is not a valid php integer'
}
?>

提前感谢!

<?php
$input = array(
    'test',
    '',
    '9000000000000000',
    '9000',
    '-9000',
    '0x1A',
    '0',
    '0x0',
    '0000'
);
function is_php_integer($strTestInput) {
    return filter_var( $strTestInput, FILTER_VALIDATE_INT, array('flags' => FILTER_FLAG_ALLOW_OCTAL | FILTER_FLAG_ALLOW_HEX));
}
foreach ( $input as $value ) {
    if (is_php_integer($value) !== FALSE) {
        echo 'your integer plus one equals: '. (intval( $value ) + 1) . PHP_EOL;
    } else {
        echo 'your input string is not a valid php integer' . PHP_EOL;
    }
}
您可以使用

filter_var。FILTER_FLAG_ALLOW_HEX标志对于0x1A0x0是必需的,FILTER_FLAG_ALLOW_OCTAL对于0000是必需的。

function is_php_integer($strInput) {
    return filter_var(
        $strInput, FILTER_VALIDATE_INT,
        FILTER_FLAG_ALLOW_OCTAL | FILTER_FLAG_ALLOW_HEX
    ) !== false;
}
function is_php_integer($strInput) {
    return false !== filter_var($strInput, FILTER_VALIDATE_INT, FILTER_FLAG_ALLOW_HEX);
}

此外,请考虑filter_input直接过滤表单数据。