Checking if a string contains an integer

后端 未结 14 645
北海茫月
北海茫月 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:48

    If you use Assert library in you project (https://github.com/beberlei/assert) you can easily do it in one line:

    Assertion::integerish($var);
    

    Note: it throws an exception in case of violation the assertion.

    0 讨论(0)
  • 2020-12-02 17:51

    If the string contains spaces, then @Jack's answer will not provide accurate result. e.g.

    $var = '19   ';
    if((string)(int)$var == $var) {
    echo 'var is an integer or a string representation of an integer';
    }
    

    The above string will not be an int according to the above check.

    So instead of using this, try following:

    if(ctype_digit(trim('19  '))){
        echo 'it is digit ';
    }else{
        echo 'it is not digit ';
    }
    
    0 讨论(0)
提交回复
热议问题