function integer($str)
{
if(preg_match('/[^0-9]/', $str))
{
return FALSE;
}
else
{
return $str;
}
}
在PHP中,是否可以为此语句创建三元运算符?
function integer($str)
{
if(preg_match('/[^0-9]/', $str))
{
return FALSE;
}
else
{
return $str;
}
}
是的:
function integer($str) {
return (preg_match('/[^0-9]/', $str) ? false : $str);
}
$str = ""
应该返回 ""
吗? - salathe你应该使用ctype_digit
:
function integer($str) {
return ctype_digit($str) ? $str : false;
}
或者使用 filter_var
和 FILTER_VALIDATE_INT
:
function integer($str) {
return filter_var($str, FILTER_VALIDATE_INT, array(
'options' => array('min_range' => 0),
'flags' => FILTER_FLAG_ALLOW_OCTAL
));
}
filter_var
可以选择性地配置允许最小和最大值,因此您也可以将其限制为仅正整数。 - GordonFILTER_FLAG_ALLOW_OCTAL
标志。 - salathefilter_var
变体相比,ctype_digit
现在看起来多好。 - NikiC
is_int
函数:http://php.net/manual/zh/function.is-int.php - Chris Laplanteis_int("4")
返回 false。 - lonesomedayis_numeric
。 - Chris Laplante