Checking if a string contains an integer

后端 未结 14 772
北海茫月
北海茫月 2020-12-02 17:10

Do you know of a function that can check if a string contains an integer?

Here\'s how I\'d expect it to work:

holds_int(\"23\") // should return true         


        
14条回答
  •  广开言路
    2020-12-02 17:40

    I've been using this since long time. While all the other answers have drawbacks or special cases, if you want to detect any possible int valued thing, including 1.0 "1.0" 1e3 "007" then you better let is_numeric do its job to detect any possible PHP object that represents a number, and only then check if that number is really an int, converting it to int and back to float, and testing if it changed value.:

    function isIntValued($var) {
        if(is_numeric($var)) { // At least it's number, can be converted to float
            $var=(float)$var; // Now it is a float
            return ((float)(int)$var)===$var;
        }
        return FALSE;
    }
    

    or in short

    function isIntValued($var) {
        return (!is_numeric($var)?FALSE:((float)(int)(float)$var)===(float)$var);
    }
    

    Or

     function isIntValued($var) {
        return (is_numeric($var) && ((float)(int)(float)$var)===(float)$var);
    }
    

    Note that while PHP's is_int() checks if the type of variable is an integer, on the contrary the other standard PHP function is_numeric() determines very accurately if the contents of the variable (i.e. string chars) can represent a number.

    If, instead, you want "1.0" and "2.00" not to be considered integers but floats (even if they have an integer value), then the other answer ( @Darragh Enright ) using is_numeric, adding zero and testing for int is probably the most correct solution:

        is_numeric($s) && is_int($s+0)
    

提交回复
热议问题