开发者

PHP validating integers

I was wondering, what would be the best way to validate an integer. I'd like this to work with strings as well, so I could to something like

(string)+00003 -> (int)3 (valid)

(string)-027 -> (int)-27 (valid)

(int)33 -> (int)33 (valid)

(string)'33a' -> (FALSE) (invalid)

That is what i've go so far:

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;
}
开发者_StackOverflow中文版

As far as I tested, this function works, but it looks like a clumsy workaround.

Is there any better way to write this kind of function. I've also tried

filter_var($foo, FILTER_VALIDATE_INT);

but it won't accept values like '0003', '-0' etc.


You could try ctype_digit or is_numeric


there is a native function called intval(). Is that's what you're looking for?


it won't accept "0003" cause it's not 'clear' integer. Integer can't start with zero but it can be negative (notice that you remove '-' with your function). As said before me, use ctype_digit or is_numeric


You could use intval as Jacob suggests.

However, if you want a Locale aware int validation class, then I suggest using the Zend Framework's Zend_Validate_Int validator.

Usage

<?php
$v = new Zend_Validate_Int();
if ($v->isValid($myVal)) {
    // yay
} else {
    // fail
}

Note that because of the pick-and-choose structure of the Zend Framework, you don't need to use this for your entire application. The Validators have minimal dependencies on Zend_Locale, for locale aware validation, and Zend_Registry.


Quick and dirty way, won't handle '0003' as far as I know.

function parseInt($in) {
    return ($in == intval($in) ? $in : false);
}


You could also use PEAR's Validate package; http://pear.php.net/manual/en/package.validate.validate.number.php

Various option are:

  1. decimal (mixed) - Decimal chars or false when decimal not allowed. For example ",." to allow both "." and ",".
  2. dec_prec (int) - Number of allowed decimals.
  3. min (float) - Minimum value.
  4. max (float) - Maximum value.
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜