开发者

How to check in PHP if a string can be transformed to integer?

开发者 https://www.devze.com 2023-03-25 21:02 出处:网络
I have strings of t开发者_运维百科he following form: \"37\", \"42\", \"7\". I need to transform them into integers. I can use intval. But I want to check if the string was in the expected format (by

I have strings of t开发者_运维百科he following form: "37", "42", "7".

I need to transform them into integers. I can use intval. But I want to check if the string was in the expected format (by not expected format I mean, for example, "abc" or "a7"). How can I do it before or after use of the intval?

As far as I know intval returns 1 if the argument was not in the appropriate format. If it is the case, there is not way to check if the argument was the good format just by analyzing the output of the intval.


You can use

ctype_digit()

http://ro2.php.net/ctype_digit


You're probably looking for filter_var.

$input = '5';
filter_var($input, FILTER_VALIDATE_INT); // returns 5
$input = 'asdf';
filter_var($input, FILTER_VALIDATE_INT); // returns false

There are also many other options you can pass into this function. I believe it was designed as a way to validate form submissions.


ctype_digit($x) && ($x == floor($x))


You can use the function is_numeric(). It should return true if it is a number, false if there are letters in the mix.


Mediocre solution, but you could do:

preg_match('/^[0-9]*$/', $value)


How about (int)$value == $value?

This would cast the value to an int, so that the left hand is definately an integer, and then checks if an untyped comparison is true.

0

精彩评论

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