Checking if a string contains an integer

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

    I liked nyson's suggestion, but noticed that it will be false for '0123'. I'm now doing this:

    (string)(int)$var === ltrim((string)$var, '0')
    

    (This would have been posted as a comment @nyson, but I don't have enough privileges to do that yet).

    Edited to add: If you want zero to be true, you need to do something like

    (int)$var === 0 || (string)(int)$var === ltrim((string)$var, '0')
    

提交回复
热议问题