如果给定的字符串不是有效数量的PHP INT类型,如何编写返回FALSE的函数,否则返回TRUE。
这在其他语言中很简单。
intval()、isint()和is_numeric()是不够的,原因如下:
is_numeric()是不够的,因为它可以匹配任何数字,而不仅仅是整数,而且它还接受大数字作为数字,而这些数字不是整数。intval()是不够的,因为它对无效的PHP整数(如'9000000000000000‘)和有效的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'
}
?>提前感谢!
发布于 2013-01-22 06:22:55
<?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;
}
}发布于 2013-01-22 06:30:47
您可以使用filter_var。FILTER_FLAG_ALLOW_HEX标志对于0x1A和0x0是必需的,而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;
}发布于 2013-01-22 06:24:28
function is_php_integer($strInput) {
return false !== filter_var($strInput, FILTER_VALIDATE_INT, FILTER_FLAG_ALLOW_HEX);
}另外,考虑使用filter_input直接过滤表单数据。
https://stackoverflow.com/questions/14448244
复制相似问题