Mik*_*ikk 1 php validation integer
我想知道,验证整数的最佳方法是什么.我也喜欢这个用字符串,所以我可以做类似的事情
(字符串)+00003 - >(int)3(有效)
(字符串)-027 - >(int)-27(有效)
(int)33 - >(int)33(有效)
(字符串)'33a' - >(FALSE)(无效)
这就是我到目前为止所做的事情:
function parseInt($int){
//If $int already is integer, return it
if(is_int($int)){return $int;}
//If not, convert it to string
$int=(string)$int;
//If we have '+' or '-' at the beginning of the string, remove them
$validate = ($int[0] === '-' || $int[0] === '+')?substr($int, 1):$int;
//If $validate matches pattern 0-9 convert $int to integer and return it
//otherwise return false
return preg_match('/^[0-9]+$/', $validate)?(int)$int:FALSE;
}
Run Code Online (Sandbox Code Playgroud)
据我测试,这个功能有效,但它看起来像一个笨拙的解决方法.
有没有更好的方法来编写这种功能.我也试过了
filter_var($foo, FILTER_VALIDATE_INT);
Run Code Online (Sandbox Code Playgroud)
但它不会接受'0003',' - 0'等值.