Checking if a string contains an integer

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

    Update Since PHP 7.1 there are problems with using is_int() with non-numeric values, as discussed in this SO Answer. In any case, this is a very old answer and I'd really view it as something of a hack at this point so YMMV ;)

    Sorry if this question has been answered but this has worked for me in the past:

    First check if the string is_numeric. if it is add a 0 to the value to get PHP to covert the string to its relevant type. Then you can check if it's an int with is_int. Quick and dirty but it works for me...

    $values = array(1, '2', '2.5', 'foo', '0xFF', 0xCC, 0644, '0777');
    
    foreach ($values as $value) {
      $result = is_numeric($value) && is_int(($value + 0)) ? 'true' : 'false';
      echo $value . ': ' . $result . '
    '; }

    Results:

    1: true
    2: true
    2.5: false
    foo: false
    0xFF: true
    204: true
    420: true
    0777: true
    

    The only problem is that it will evaluate octal values wrapped in a string literally, i.e: '0123' will simply become 123. But that's easy to address :)

提交回复
热议问题