PHP has an intval()
function that will convert a string to an integer. However I want to check that the string is an integer beforehand, so that I can give a helpful error message to the user if it's wrong. PHP has is_int()
, but that returns false for string like "2"
.
PHP有一个intval()函数,它将字符串转换为整数。但是,我想检查一下字符串是否是一个整数,这样我就可以给用户一个有用的错误消息。PHP有is_int(),但是对于像“2”这样的字符串返回false。
PHP has the is_numeric()
function, but that will return true if the number is a double. I want something that will return false for a double, but true for an int.
PHP具有is_numeric()函数,但是如果数字是双精度的,则返回true。我想要一个返回false的双精度浮点数,但是返回true的整数。
e.g.:
例如:
my_is_int("2") == TRUE
my_is_int("2.1") == FALSE
22 个解决方案
#1
133
How about using ctype_digit
?
使用ctype_digit怎么样?
From the manual:
从手册:
<?php
$strings = array('1820.20', '10002', 'wsl!12');
foreach ($strings as $testcase) {
if (ctype_digit($testcase)) {
echo "The string $testcase consists of all digits.\n";
} else {
echo "The string $testcase does not consist of all digits.\n";
}
}
?>
The above example will output:
上面的示例将输出:
The string 1820.20 does not consist of all digits. The string 10002 consists of all digits. The string wsl!12 does not consist of all digits.
This will only work if your input is always a string:
只有当您的输入始终是字符串时,这才会有效:
$numeric_string = '42';
$integer = 42;
ctype_digit($numeric_string); // true
ctype_digit($integer); // false
If your input might be of type int
, then combine ctype_digit
with is_int
.
如果输入可能是int类型,那么将ctype_digit与is_int组合起来。
If you care about negative numbers, then you'll need to check the input for a preceding -
, and if so, call ctype_digit
on a substr
of the input string. Something like this would do it:
如果您关心负数,那么您将需要检查前面的输入,如果是,请调用输入字符串的子str上的ctype_digit。像这样的东西可以做到:
function my_is_int($input) {
if ($input[0] == '-') {
return ctype_digit(substr($input, 1));
}
return ctype_digit($input);
}
#2
67
filter_var
should do it:
使用filter_var应该这样做:
var_dump(filter_var('2', FILTER_VALIDATE_INT)); // 2
var_dump(filter_var('2.0', FILTER_VALIDATE_INT)); // false
var_dump(filter_var('2.1', FILTER_VALIDATE_INT)); // false
but
但
var_dump(filter_var(2, FILTER_VALIDATE_INT)); // 2
var_dump(filter_var(2.0, FILTER_VALIDATE_INT)); // 2
var_dump(filter_var(2.1, FILTER_VALIDATE_INT)); // false
If you just want Booleans as return values, wrap it into a function, e.g.
如果您只是想将布尔值作为返回值,请将其封装到一个函数中。
function validatesAsInt($number)
{
$number = filter_var($number, FILTER_VALIDATE_INT);
return ($number !== FALSE);
}
#3
16
+1 to Dominic's answer (using ctype_digit
). Another way you could do it is with type coercion:
+1到多米尼克的答案(使用ctype_digit)。另一种方法是类型强制:
$inty = "2";
$inty2 = " 2";
$floaty = "2.1";
$floaty2 = "2.0";
is_int($inty + 0); // true
is_int($floaty + 0); // false
is_int($floaty2 + 0); // false
// here's difference between this and the ctype functions.
is_int($inty2 + 0); // true
ctype_digit($inty2); // false
#4
11
Cast it to int. if it still have the same value its int;
如果它仍然具有相同的值,则将它转换为int;
function my_is_int($var) {
$tmp = (int) $var;
if($tmp == $var)
return true;
else
return false;
}
#5
6
Had a need for a robust is_int
recently. I found intval() too unpredictable:
最近需要一个健壮的is_int。我发现intval()太不可预测了:
intval(array('foo', 'bar')) //returns 1 ?!?
intval("2dog") //returns 2 even though the value is definitely not an integer
intval("dog2") //also returns 2
Came across this snippet in the PHP documentation comments, and after testing it, it covers almost everything you throw at it:
在PHP文档注释中偶然发现了这段代码,经过测试,它几乎涵盖了您所遇到的所有内容:
function my_is_int($s) {
return (is_numeric($s) ? intval($s) == $s : false);
}
my_is_int(2); //true
my_is_int("2"); //true
my_is_int(2.1); //false
my_is_int("2.1"); //false
my_is_int("dog"); //false
my_is_int("2dog"); //false
my_is_int("dog2"); //false
my_is_int(array('foo', 'bar')); //false
my_is_int(array(1)); //false
But careful:
但注意:
my_is_int(2.0); //true
my_is_int("2.0"); //true
#6
6
/**
* Check if a number is a counting number by checking if it
* is an integer primitive type, or if the string represents
* an integer as a string
*/
function is_int_val($data) {
if (is_int($data) === true) return true;
if (is_string($data) === true && is_numeric($data) === true) {
return (strpos($data, '.') === false);
}
}
源。
#7
4
function my_is_int($var) {
return preg_match('/^\d+$/', $var);
}
#8
3
I´m using this one:
使用这一个我´m:
function isInt($val){
return (filter_var($val, FILTER_VALIDATE_INT) !== false && strpos($val, '-') === false);
}
var_dump (isInt("1"));
#9
3
You can just check for a number, if it is then check than casting is given a double or not:
你可以只检查一个数字,如果它是,然后检查比铸造给一个双重或不:
((is_numeric($var) && !is_double(1*$var)));
Just for positive numbers:
只是为了积极的数字:
(is_numeric($var) && !is_double(1*$var)) && ($var >= 0)
Checking it:
检查:
$numbersToCheck = array("a", "-1", "1", "1.0", "1.2");
foreach ($numbersToCheck as $var) {
echo $var . " is integer? ";var_dump((is_numeric($var) && !is_double(1*$var)));
echo $var . " is a positive integer? ";var_dump((is_numeric($var) && !is_double(1*$var)) && ($var >= 0));
}
Output:
输出:
a is integer? bool(false)
a is a positive integer? bool(false)
-1 is integer? bool(true)
-1 is a positive integer? bool(false)
1 is integer? bool(true)
1 is a positive integer? bool(true)
1.0 is integer? bool(false)
1.0 is a positive integer? bool(false)
1.2 is integer? bool(false)
1.2 is a positive integer? bool(false)
#10
2
Try this:
试试这个:
$string='12abc';
if ((int)$string==$string) var_dump((int)$string); else echo 'Invalid!';
// Outputs: Invalid!
$string='789';
if ((int)$string==$string) var_dump((int)$string); else echo 'Invalid!';
// Outputs: int 789
$string='345.00';
if ((int)$string==$string) var_dump((int)$string); else echo 'Invalid!';
// Outputs: 345
$string='123.01';
if ((int)$string==$string) var_dump((int)$string); else echo 'Invalid!';
// Outputs: Invalid!
Also works if your $string has decimal places
如果您的$string有十进制位,也可以
#11
2
This will take care of negative number as well
这也会照顾到负数。
function myIsInt()
{
return (is_numeric($var) AND (is_int($var) OR ctype_digit(trim($var, '-'))))
}
//'234-' => false
//'-234' => true
//'--234' => false
//'234' => true
#12
2
Maybe not the most performant way of doing it. But you can write it in one line.
也许不是最有效的方法。但是你可以把它写在一行里。
function my_is_int($input) {
return intval($input).'' === $input.'';
}
As expected:
像预期的那样:
my_is_int(1); // TRUE
my_is_int(-1); // TRUE
my_is_int(1.2); // FALSE
my_is_int("1"); // TRUE
my_is_int("-1"); // TRUE
my_is_int("1.2"); // FALSE
my_is_int(0); // TRUE
my_is_int(null); // FALSE
Gotcha:
问题:
my_is_int(1.0); // TRUE
my_is_int("1.0"); // FALSE
#13
1
How about:
如何:
function isIntStr($str) {
return preg_match('/^(-?\d+)(?:\.0+)?$/', trim($str), $ms)
&& bcComp($ms[1], PHP_INT_MAX) <= 0
&& bcComp($ms[1], -PHP_INT_MAX - 1) >= 0;
}
This function should only return true for any string number that can be cast to int with (int)
or intval()
without losing anything of mathematical significance (such as non-zeros after decimal point or numbers outside of PHP's integer range) while accepting things that aren't mathematically significant (such as whitespace; leading zeros; or, after the decimal point, zeros exclusively).
这个函数应该只对任何可以用(int)或intval()转换为int的字符串返回true,而不丢失任何具有数学意义的东西(比如小数点后的非零值或PHP整数范围之外的数字),同时接受没有数学意义的东西(比如空格);前导零;或者,在小数点后,完全是零)。
It will return false for '10.'
but not for '10.0'
. If you wanted '10.'
to be true you could change the +
after the 0
in the regular expression to *
.
它将返回false。但不是“10.0”。如果你想要的10。'如果是真的,你可以把正则表达式中的0后面的+改成*。
#14
1
Here some code I've used that seems to work well and doesn't have any of the issues that many of the others do.
在这里,我使用的一些代码似乎工作得很好,并且不像其他许多代码那样存在任何问题。
if (0 != strlen(str_replace(range(0, 9), '', $TestInt))) { print 'Not an integer!';}
It does not check order etc so not meant for negative integers but with some addition code that can be done as well using some of the other ideas from above. It can also be adapted to work with binary array('0', '1')
or Hexadecimals as well etc.
它不检查顺序等等,所以不是为负整数,而是用一些加法代码,也可以使用上面的其他思想。它还可以用于二进制数组('0','1')或十六进制等。
#15
1
See this. Converts $val to integer and then checks if the original $val converted to string is IDENTICAL (===) - just == won't work as expected - to the integer val converted to string.
看到这个。将$val转换为integer,然后检查转换为string的原始$val是否与转换为string的integer val相同(===)—只是==不能正常工作。
function validInt($val, $min=null, $max=null) {
$ival = intval($val);
//echo "'$ival' '$val'<br>\n"; // Uncomment to see the comparisons done in below if block
if(''.$ival !== ''.$val) {
return false;
}
if($min !== null && $ival < $min)
return false;
if($max !== null && $ival > $max)
return false;
return true;
}
If you don't check string values it might not work as you expect it:
如果不检查字符串值,它可能不会像您期望的那样工作:
$nums = array(
'1',
'+1',
'-1',
'01',
'1.0',
'.0',
'1.123',
'a123',
'0x101010',
1,
-1,
01,
1.0,
.0,
1.123,
0x101010,
);
foreach($nums as $num) {
if(validInt2($num))
echo $num." - Valid integer.<br>\n";
else
echo $num." - Not a valid integer.<br>\n";
}
Output:
输出:
1 - Valid integer.
+1 - Not a valid integer.
-1 - Valid integer.
01 - Not a valid integer.
1.0 - Not a valid integer.
.0 - Not a valid integer.
1.123 - Not a valid integer.
a123 - Not a valid integer.
0x101010 - Not a valid integer.
1 - Valid integer.
-1 - Valid integer.
1 - Valid integer.
1 - Valid integer.
0 - Valid integer.
1.123 - Not a valid integer.
1052688 - Valid integer.
Reason being even if you use hex (0x101010), octal (01) or an integer stored as float (1.0, 0.0), internally all are stored as float. However, if you use the function to check for int stored as a string, it will work.
原因是,即使您使用十六进制(0x101010)、八进制(01)或一个以浮点数(1.0,0.0)存储的整数,在内部也都以浮点数存储。但是,如果您使用这个函数检查作为字符串存储的int,它将会工作。
#16
1
public static function isNumeric($value, $negativ = false) {
return is_int($value) || is_string($value) && (
ctype_digit($value) || (
$negativ && $value{0} == '-' && ctype_digit(substr($value, 1))
)
);
//alternativ:
//return $value == (int) $value;
}
#17
1
function my_is_int($var){
return is_numeric($var) && gettype($var+0)=='integer';
}
#18
1
You can use the following condition. Notice that you should not use !==
您可以使用以下条件。注意,您不应该使用!=
$value = 12; // true
$value = '12'; // true
$value = 'abc'; // false
$value = 12.1; // false
$value = '12.1'; // false
if (!is_numeric($value) || (int) $value != (float) $value) {
echo "false";
} else {
echo "true";
}
#19
1
I devised a way I couldn't find anywhere, so I'm putting it in here:
我设计了一种找不到任何地方的方法,所以我把它放在这里:
Without further ado it's this: ctype_digit((string) abs($input))
不再赘述,它是:ctype_digit(字符串)abs($input))
Example:
例子:
function means_int($input) {
return ctype_digit((string) abs($input));
}
$list = array(
0,
'0',
1,
'1',
1.1,
'1.1',
2.0,
'2.0',
2.6,
'2.6',
-4,
'-4',
-3.2,
'-3.2',
-30.02,
'-30.02',
100.00,
'100.00',
);
foreach ($list as $x) {
var_dump($x);
var_dump(means_int($x));
echo PHP_EOL;
}
Results: (are as expected, I suppose)
结果:(如预期)
int(0)
bool(true)
string(1) "0"
bool(true)
int(1)
bool(true)
string(1) "1"
bool(true)
float(1.1)
bool(false)
string(3) "1.1"
bool(false)
float(2)
bool(true)
string(3) "2.0"
bool(true)
float(2.6)
bool(false)
string(3) "2.6"
bool(false)
int(-4)
bool(true)
string(2) "-4"
bool(true)
float(-3.2)
bool(false)
string(4) "-3.2"
bool(false)
float(-30.02)
bool(false)
string(6) "-30.02"
bool(false)
float(100)
bool(true)
string(6) "100.00"
bool(true)
#20
1
A few years late, but based on the answers given here I came up with a solution that's slightly more accurate (on booleans, in particular) and more efficient (I think) than most other answers:
虽然晚了几年,但基于这里给出的答案,我想出了一个比其他大多数答案更精确的解决方案(尤其是布尔人)和更有效率的(我认为):
function my_is_int($s) {
return ctype_digit($s) || is_int($s);
}
Working as expected for these:
按照预期工作:
my_is_int(2); // true
my_is_int("2"); // true
my_is_int(-2); // true
my_is_int(2.0); // false
my_is_int("2.0"); // false
my_is_int(2.1); // false
my_is_int("2.1"); // false
my_is_int("dog"); // false
my_is_int("2dog"); // false
my_is_int("dog2"); // false
my_is_int(array('foo', 'bar')); // false
my_is_int(array(1)); // false
my_is_int(true); // false
my_is_int(false); // false
my_is_int("true"); // false
my_is_int("false"); // false
my_is_int("0x101010"); // false
Except maybe for these 2:
除了这两个
my_is_int(0x101010); // true
my_is_int("-2"); // false
#21
-1
Could either use is_numeric() then check for presence of "." in the string (not particularly culture-sensitive though).
可以使用is_numeric(),然后检查字符串中是否存在“.”(虽然不是特别关注区域性)。
Alternatively use is_numeric() then cast to a double and see if $var == floor($var) (should return true if it's an integer).
或者使用is_numeric(),然后转换为double,查看$var == floor($var)(如果它是整数,应该返回true)。
#22
-1
If you want to genuinely know if a string is a valid representation of a true PHP integer type...
如果您真的想知道一个字符串是否是一个真正的PHP整数类型的有效表示……
in_array($string, array_map('strval', range(PHP_INT_MIN, PHP_INT_MAX)), true)
However this is impossible to run as the set is too large (will not fit in memory in this case, if you loop instead it will take too many CPU cycles).
但是,这是不可能运行的,因为集合太大了(在这种情况下不适合内存,如果您循环,它将花费太多的CPU周期)。
You can perhaps do a binary search with string comparison, however there are better ways.
您可以使用字符串比较进行二进制搜索,但是有更好的方法。
The simplest being:
最简单的是:
strlen($string) <= max(strlen((string)PHP_INT_MIN), strlen((string)PHP_INT_MAX)) && $string === (string)(int)$string
There are some other unusual ways to approach it such as:
还有其他一些不同寻常的方法来解决这个问题,比如:
is_int(array_keys([$string => null])[0])
You can also do string comparison but you'll still need to do things such as ctype_digit, check the length is reasonable (don't waste CPU before doing things like ctype_digit) and have some awkward handling for negative numbers.
您也可以进行字符串比较,但是您仍然需要做一些事情,比如ctype_digit,检查长度是否合理(在执行ctype_digit之类的操作之前不要浪费CPU),以及处理负数的问题。
Note that filter_var does not correctly assert that a string is genuinely the representation of a PHP integer. It will allow a leading + and surrounding whitespace.
注意,filter_var并没有正确地断言字符串实际上是PHP整数的表示。它将允许前导+和周围的空格。
Internally PHP uses the function "_zend_handle_numeric_str" for strict comparison but it doesn't directly expose this anywhere, hence the trick using the array keys (which does use it to convert any string that's a representation of a PHP integer to a PHP integer).
PHP内部使用函数“_zend_handle_numeric_str”进行严格的比较,但它不会在任何地方直接公开这个函数,因此使用数组键(它确实使用数组键将PHP整数表示的任何字符串转换为PHP整数)。
If you want binary safe conversion to and from PHP this is the approach to take.
如果你想要二进制安全转换到和从PHP,这是采取的方法。
Not everyone might want that and it might be a case of handling user input. filter_var isn't too bad for that and will be fairly safe in most cases for people new to PHP.
不是每个人都想这样,这可能是一个处理用户输入的例子。filter_var并不是很糟糕,在大多数情况下对于PHP新手来说都是相当安全的。
A length check, ctype_digit and then a check of converted value that it's in a range is also fairly solid for user input. More complex schemes might want trim or regex.
长度检查,ctype_digit以及它所在范围内的转换值检查对于用户输入也是相当可靠的。更复杂的方案可能需要修剪或正则表达式。
The problem with a lot of the answers here in that respect is that while the question is vague, the answers shouldn't be. If you're going to propose a solution you should be able to explain exactly what it will and wont expect. Without that there's no telling if an answer matches a question or is safe. The PHP manual does not always help because it doesn't explain all of the caveats for each of the relevant methods it supplies. Things such as ctype_digit and is_int are very reliable and easy to predit but the specifics of is_numeric, filter_var and juggling (+$var) or casting (intval/floatval) are poorly documented.
在这方面,很多答案的问题在于,虽然问题是模糊的,但答案不应该是模糊的。如果你要提出一个解决方案,你应该能够准确地解释它将会和不会期望的。如果没有这个答案,就无法判断答案是否与问题相符或是否安全。PHP手册并不总是有帮助,因为它没有解释它提供的每个相关方法的所有注意事项。像ctype_digit和is_int这样的东西是非常可靠和容易预编的,但是is_numeric、filter_var和戏法(+$var)或cast (intval/floatval)的细节都没有详细的文档说明。
This is PHP fudge for you. It has a myriad number of schemas for interpreting strings as integers, with inconsistencies. The strictest method of validating an integer string is not directly exposed to the user.
这是PHP软糖。它有无数的模式来将字符串解释为整数,并且不一致。验证整数字符串的最严格方法不是直接向用户公开的。
#1
133
How about using ctype_digit
?
使用ctype_digit怎么样?
From the manual:
从手册:
<?php
$strings = array('1820.20', '10002', 'wsl!12');
foreach ($strings as $testcase) {
if (ctype_digit($testcase)) {
echo "The string $testcase consists of all digits.\n";
} else {
echo "The string $testcase does not consist of all digits.\n";
}
}
?>
The above example will output:
上面的示例将输出:
The string 1820.20 does not consist of all digits. The string 10002 consists of all digits. The string wsl!12 does not consist of all digits.
This will only work if your input is always a string:
只有当您的输入始终是字符串时,这才会有效:
$numeric_string = '42';
$integer = 42;
ctype_digit($numeric_string); // true
ctype_digit($integer); // false
If your input might be of type int
, then combine ctype_digit
with is_int
.
如果输入可能是int类型,那么将ctype_digit与is_int组合起来。
If you care about negative numbers, then you'll need to check the input for a preceding -
, and if so, call ctype_digit
on a substr
of the input string. Something like this would do it:
如果您关心负数,那么您将需要检查前面的输入,如果是,请调用输入字符串的子str上的ctype_digit。像这样的东西可以做到:
function my_is_int($input) {
if ($input[0] == '-') {
return ctype_digit(substr($input, 1));
}
return ctype_digit($input);
}
#2
67
filter_var
should do it:
使用filter_var应该这样做:
var_dump(filter_var('2', FILTER_VALIDATE_INT)); // 2
var_dump(filter_var('2.0', FILTER_VALIDATE_INT)); // false
var_dump(filter_var('2.1', FILTER_VALIDATE_INT)); // false
but
但
var_dump(filter_var(2, FILTER_VALIDATE_INT)); // 2
var_dump(filter_var(2.0, FILTER_VALIDATE_INT)); // 2
var_dump(filter_var(2.1, FILTER_VALIDATE_INT)); // false
If you just want Booleans as return values, wrap it into a function, e.g.
如果您只是想将布尔值作为返回值,请将其封装到一个函数中。
function validatesAsInt($number)
{
$number = filter_var($number, FILTER_VALIDATE_INT);
return ($number !== FALSE);
}
#3
16
+1 to Dominic's answer (using ctype_digit
). Another way you could do it is with type coercion:
+1到多米尼克的答案(使用ctype_digit)。另一种方法是类型强制:
$inty = "2";
$inty2 = " 2";
$floaty = "2.1";
$floaty2 = "2.0";
is_int($inty + 0); // true
is_int($floaty + 0); // false
is_int($floaty2 + 0); // false
// here's difference between this and the ctype functions.
is_int($inty2 + 0); // true
ctype_digit($inty2); // false
#4
11
Cast it to int. if it still have the same value its int;
如果它仍然具有相同的值,则将它转换为int;
function my_is_int($var) {
$tmp = (int) $var;
if($tmp == $var)
return true;
else
return false;
}
#5
6
Had a need for a robust is_int
recently. I found intval() too unpredictable:
最近需要一个健壮的is_int。我发现intval()太不可预测了:
intval(array('foo', 'bar')) //returns 1 ?!?
intval("2dog") //returns 2 even though the value is definitely not an integer
intval("dog2") //also returns 2
Came across this snippet in the PHP documentation comments, and after testing it, it covers almost everything you throw at it:
在PHP文档注释中偶然发现了这段代码,经过测试,它几乎涵盖了您所遇到的所有内容:
function my_is_int($s) {
return (is_numeric($s) ? intval($s) == $s : false);
}
my_is_int(2); //true
my_is_int("2"); //true
my_is_int(2.1); //false
my_is_int("2.1"); //false
my_is_int("dog"); //false
my_is_int("2dog"); //false
my_is_int("dog2"); //false
my_is_int(array('foo', 'bar')); //false
my_is_int(array(1)); //false
But careful:
但注意:
my_is_int(2.0); //true
my_is_int("2.0"); //true
#6
6
/**
* Check if a number is a counting number by checking if it
* is an integer primitive type, or if the string represents
* an integer as a string
*/
function is_int_val($data) {
if (is_int($data) === true) return true;
if (is_string($data) === true && is_numeric($data) === true) {
return (strpos($data, '.') === false);
}
}
源。
#7
4
function my_is_int($var) {
return preg_match('/^\d+$/', $var);
}
#8
3
I´m using this one:
使用这一个我´m:
function isInt($val){
return (filter_var($val, FILTER_VALIDATE_INT) !== false && strpos($val, '-') === false);
}
var_dump (isInt("1"));
#9
3
You can just check for a number, if it is then check than casting is given a double or not:
你可以只检查一个数字,如果它是,然后检查比铸造给一个双重或不:
((is_numeric($var) && !is_double(1*$var)));
Just for positive numbers:
只是为了积极的数字:
(is_numeric($var) && !is_double(1*$var)) && ($var >= 0)
Checking it:
检查:
$numbersToCheck = array("a", "-1", "1", "1.0", "1.2");
foreach ($numbersToCheck as $var) {
echo $var . " is integer? ";var_dump((is_numeric($var) && !is_double(1*$var)));
echo $var . " is a positive integer? ";var_dump((is_numeric($var) && !is_double(1*$var)) && ($var >= 0));
}
Output:
输出:
a is integer? bool(false)
a is a positive integer? bool(false)
-1 is integer? bool(true)
-1 is a positive integer? bool(false)
1 is integer? bool(true)
1 is a positive integer? bool(true)
1.0 is integer? bool(false)
1.0 is a positive integer? bool(false)
1.2 is integer? bool(false)
1.2 is a positive integer? bool(false)
#10
2
Try this:
试试这个:
$string='12abc';
if ((int)$string==$string) var_dump((int)$string); else echo 'Invalid!';
// Outputs: Invalid!
$string='789';
if ((int)$string==$string) var_dump((int)$string); else echo 'Invalid!';
// Outputs: int 789
$string='345.00';
if ((int)$string==$string) var_dump((int)$string); else echo 'Invalid!';
// Outputs: 345
$string='123.01';
if ((int)$string==$string) var_dump((int)$string); else echo 'Invalid!';
// Outputs: Invalid!
Also works if your $string has decimal places
如果您的$string有十进制位,也可以
#11
2
This will take care of negative number as well
这也会照顾到负数。
function myIsInt()
{
return (is_numeric($var) AND (is_int($var) OR ctype_digit(trim($var, '-'))))
}
//'234-' => false
//'-234' => true
//'--234' => false
//'234' => true
#12
2
Maybe not the most performant way of doing it. But you can write it in one line.
也许不是最有效的方法。但是你可以把它写在一行里。
function my_is_int($input) {
return intval($input).'' === $input.'';
}
As expected:
像预期的那样:
my_is_int(1); // TRUE
my_is_int(-1); // TRUE
my_is_int(1.2); // FALSE
my_is_int("1"); // TRUE
my_is_int("-1"); // TRUE
my_is_int("1.2"); // FALSE
my_is_int(0); // TRUE
my_is_int(null); // FALSE
Gotcha:
问题:
my_is_int(1.0); // TRUE
my_is_int("1.0"); // FALSE
#13
1
How about:
如何:
function isIntStr($str) {
return preg_match('/^(-?\d+)(?:\.0+)?$/', trim($str), $ms)
&& bcComp($ms[1], PHP_INT_MAX) <= 0
&& bcComp($ms[1], -PHP_INT_MAX - 1) >= 0;
}
This function should only return true for any string number that can be cast to int with (int)
or intval()
without losing anything of mathematical significance (such as non-zeros after decimal point or numbers outside of PHP's integer range) while accepting things that aren't mathematically significant (such as whitespace; leading zeros; or, after the decimal point, zeros exclusively).
这个函数应该只对任何可以用(int)或intval()转换为int的字符串返回true,而不丢失任何具有数学意义的东西(比如小数点后的非零值或PHP整数范围之外的数字),同时接受没有数学意义的东西(比如空格);前导零;或者,在小数点后,完全是零)。
It will return false for '10.'
but not for '10.0'
. If you wanted '10.'
to be true you could change the +
after the 0
in the regular expression to *
.
它将返回false。但不是“10.0”。如果你想要的10。'如果是真的,你可以把正则表达式中的0后面的+改成*。
#14
1
Here some code I've used that seems to work well and doesn't have any of the issues that many of the others do.
在这里,我使用的一些代码似乎工作得很好,并且不像其他许多代码那样存在任何问题。
if (0 != strlen(str_replace(range(0, 9), '', $TestInt))) { print 'Not an integer!';}
It does not check order etc so not meant for negative integers but with some addition code that can be done as well using some of the other ideas from above. It can also be adapted to work with binary array('0', '1')
or Hexadecimals as well etc.
它不检查顺序等等,所以不是为负整数,而是用一些加法代码,也可以使用上面的其他思想。它还可以用于二进制数组('0','1')或十六进制等。
#15
1
See this. Converts $val to integer and then checks if the original $val converted to string is IDENTICAL (===) - just == won't work as expected - to the integer val converted to string.
看到这个。将$val转换为integer,然后检查转换为string的原始$val是否与转换为string的integer val相同(===)—只是==不能正常工作。
function validInt($val, $min=null, $max=null) {
$ival = intval($val);
//echo "'$ival' '$val'<br>\n"; // Uncomment to see the comparisons done in below if block
if(''.$ival !== ''.$val) {
return false;
}
if($min !== null && $ival < $min)
return false;
if($max !== null && $ival > $max)
return false;
return true;
}
If you don't check string values it might not work as you expect it:
如果不检查字符串值,它可能不会像您期望的那样工作:
$nums = array(
'1',
'+1',
'-1',
'01',
'1.0',
'.0',
'1.123',
'a123',
'0x101010',
1,
-1,
01,
1.0,
.0,
1.123,
0x101010,
);
foreach($nums as $num) {
if(validInt2($num))
echo $num." - Valid integer.<br>\n";
else
echo $num." - Not a valid integer.<br>\n";
}
Output:
输出:
1 - Valid integer.
+1 - Not a valid integer.
-1 - Valid integer.
01 - Not a valid integer.
1.0 - Not a valid integer.
.0 - Not a valid integer.
1.123 - Not a valid integer.
a123 - Not a valid integer.
0x101010 - Not a valid integer.
1 - Valid integer.
-1 - Valid integer.
1 - Valid integer.
1 - Valid integer.
0 - Valid integer.
1.123 - Not a valid integer.
1052688 - Valid integer.
Reason being even if you use hex (0x101010), octal (01) or an integer stored as float (1.0, 0.0), internally all are stored as float. However, if you use the function to check for int stored as a string, it will work.
原因是,即使您使用十六进制(0x101010)、八进制(01)或一个以浮点数(1.0,0.0)存储的整数,在内部也都以浮点数存储。但是,如果您使用这个函数检查作为字符串存储的int,它将会工作。
#16
1
public static function isNumeric($value, $negativ = false) {
return is_int($value) || is_string($value) && (
ctype_digit($value) || (
$negativ && $value{0} == '-' && ctype_digit(substr($value, 1))
)
);
//alternativ:
//return $value == (int) $value;
}
#17
1
function my_is_int($var){
return is_numeric($var) && gettype($var+0)=='integer';
}
#18
1
You can use the following condition. Notice that you should not use !==
您可以使用以下条件。注意,您不应该使用!=
$value = 12; // true
$value = '12'; // true
$value = 'abc'; // false
$value = 12.1; // false
$value = '12.1'; // false
if (!is_numeric($value) || (int) $value != (float) $value) {
echo "false";
} else {
echo "true";
}
#19
1
I devised a way I couldn't find anywhere, so I'm putting it in here:
我设计了一种找不到任何地方的方法,所以我把它放在这里:
Without further ado it's this: ctype_digit((string) abs($input))
不再赘述,它是:ctype_digit(字符串)abs($input))
Example:
例子:
function means_int($input) {
return ctype_digit((string) abs($input));
}
$list = array(
0,
'0',
1,
'1',
1.1,
'1.1',
2.0,
'2.0',
2.6,
'2.6',
-4,
'-4',
-3.2,
'-3.2',
-30.02,
'-30.02',
100.00,
'100.00',
);
foreach ($list as $x) {
var_dump($x);
var_dump(means_int($x));
echo PHP_EOL;
}
Results: (are as expected, I suppose)
结果:(如预期)
int(0)
bool(true)
string(1) "0"
bool(true)
int(1)
bool(true)
string(1) "1"
bool(true)
float(1.1)
bool(false)
string(3) "1.1"
bool(false)
float(2)
bool(true)
string(3) "2.0"
bool(true)
float(2.6)
bool(false)
string(3) "2.6"
bool(false)
int(-4)
bool(true)
string(2) "-4"
bool(true)
float(-3.2)
bool(false)
string(4) "-3.2"
bool(false)
float(-30.02)
bool(false)
string(6) "-30.02"
bool(false)
float(100)
bool(true)
string(6) "100.00"
bool(true)
#20
1
A few years late, but based on the answers given here I came up with a solution that's slightly more accurate (on booleans, in particular) and more efficient (I think) than most other answers:
虽然晚了几年,但基于这里给出的答案,我想出了一个比其他大多数答案更精确的解决方案(尤其是布尔人)和更有效率的(我认为):
function my_is_int($s) {
return ctype_digit($s) || is_int($s);
}
Working as expected for these:
按照预期工作:
my_is_int(2); // true
my_is_int("2"); // true
my_is_int(-2); // true
my_is_int(2.0); // false
my_is_int("2.0"); // false
my_is_int(2.1); // false
my_is_int("2.1"); // false
my_is_int("dog"); // false
my_is_int("2dog"); // false
my_is_int("dog2"); // false
my_is_int(array('foo', 'bar')); // false
my_is_int(array(1)); // false
my_is_int(true); // false
my_is_int(false); // false
my_is_int("true"); // false
my_is_int("false"); // false
my_is_int("0x101010"); // false
Except maybe for these 2:
除了这两个
my_is_int(0x101010); // true
my_is_int("-2"); // false
#21
-1
Could either use is_numeric() then check for presence of "." in the string (not particularly culture-sensitive though).
可以使用is_numeric(),然后检查字符串中是否存在“.”(虽然不是特别关注区域性)。
Alternatively use is_numeric() then cast to a double and see if $var == floor($var) (should return true if it's an integer).
或者使用is_numeric(),然后转换为double,查看$var == floor($var)(如果它是整数,应该返回true)。
#22
-1
If you want to genuinely know if a string is a valid representation of a true PHP integer type...
如果您真的想知道一个字符串是否是一个真正的PHP整数类型的有效表示……
in_array($string, array_map('strval', range(PHP_INT_MIN, PHP_INT_MAX)), true)
However this is impossible to run as the set is too large (will not fit in memory in this case, if you loop instead it will take too many CPU cycles).
但是,这是不可能运行的,因为集合太大了(在这种情况下不适合内存,如果您循环,它将花费太多的CPU周期)。
You can perhaps do a binary search with string comparison, however there are better ways.
您可以使用字符串比较进行二进制搜索,但是有更好的方法。
The simplest being:
最简单的是:
strlen($string) <= max(strlen((string)PHP_INT_MIN), strlen((string)PHP_INT_MAX)) && $string === (string)(int)$string
There are some other unusual ways to approach it such as:
还有其他一些不同寻常的方法来解决这个问题,比如:
is_int(array_keys([$string => null])[0])
You can also do string comparison but you'll still need to do things such as ctype_digit, check the length is reasonable (don't waste CPU before doing things like ctype_digit) and have some awkward handling for negative numbers.
您也可以进行字符串比较,但是您仍然需要做一些事情,比如ctype_digit,检查长度是否合理(在执行ctype_digit之类的操作之前不要浪费CPU),以及处理负数的问题。
Note that filter_var does not correctly assert that a string is genuinely the representation of a PHP integer. It will allow a leading + and surrounding whitespace.
注意,filter_var并没有正确地断言字符串实际上是PHP整数的表示。它将允许前导+和周围的空格。
Internally PHP uses the function "_zend_handle_numeric_str" for strict comparison but it doesn't directly expose this anywhere, hence the trick using the array keys (which does use it to convert any string that's a representation of a PHP integer to a PHP integer).
PHP内部使用函数“_zend_handle_numeric_str”进行严格的比较,但它不会在任何地方直接公开这个函数,因此使用数组键(它确实使用数组键将PHP整数表示的任何字符串转换为PHP整数)。
If you want binary safe conversion to and from PHP this is the approach to take.
如果你想要二进制安全转换到和从PHP,这是采取的方法。
Not everyone might want that and it might be a case of handling user input. filter_var isn't too bad for that and will be fairly safe in most cases for people new to PHP.
不是每个人都想这样,这可能是一个处理用户输入的例子。filter_var并不是很糟糕,在大多数情况下对于PHP新手来说都是相当安全的。
A length check, ctype_digit and then a check of converted value that it's in a range is also fairly solid for user input. More complex schemes might want trim or regex.
长度检查,ctype_digit以及它所在范围内的转换值检查对于用户输入也是相当可靠的。更复杂的方案可能需要修剪或正则表达式。
The problem with a lot of the answers here in that respect is that while the question is vague, the answers shouldn't be. If you're going to propose a solution you should be able to explain exactly what it will and wont expect. Without that there's no telling if an answer matches a question or is safe. The PHP manual does not always help because it doesn't explain all of the caveats for each of the relevant methods it supplies. Things such as ctype_digit and is_int are very reliable and easy to predit but the specifics of is_numeric, filter_var and juggling (+$var) or casting (intval/floatval) are poorly documented.
在这方面,很多答案的问题在于,虽然问题是模糊的,但答案不应该是模糊的。如果你要提出一个解决方案,你应该能够准确地解释它将会和不会期望的。如果没有这个答案,就无法判断答案是否与问题相符或是否安全。PHP手册并不总是有帮助,因为它没有解释它提供的每个相关方法的所有注意事项。像ctype_digit和is_int这样的东西是非常可靠和容易预编的,但是is_numeric、filter_var和戏法(+$var)或cast (intval/floatval)的细节都没有详细的文档说明。
This is PHP fudge for you. It has a myriad number of schemas for interpreting strings as integers, with inconsistencies. The strictest method of validating an integer string is not directly exposed to the user.
这是PHP软糖。它有无数的模式来将字符串解释为整数,并且不一致。验证整数字符串的最严格方法不是直接向用户公开的。