如何测试字符串是否包含整数的表示形式,而不包含其他任何内容


How to test whether a string contains the representation of an integer and nothing else?

PHP中是否有一个函数可以将字符串转换为int,但是认真对待"int"。

转换为 int 或 intval 都试图变得聪明并执行额外的数学运算,如舍入。

我有一个解决方案 - 使用 int cast,然后将 int 转换回字符串。

如果结果相同,则确定,但如果不是,则表示字符串表示其他内容(例如浮点数)。

"2.2" --> 2 --> "2" --> fail
"3" --> 3 --> "3" --> OK

但是我想知道是否有一些准备好在 PHP 中使用的东西?

您可以使用以下函数:

function StrictIntVal($x)
{
  // If we already have an integer
  if(is_int($x)) return $x;
  // Check we have a string
  if(!is_string($x)) return false;
  // Check the string only contains digits (and optional sign)
  if(!preg_match("/^['+'-]?'d+$/", $x)) return false;
  return intval($x);
}

可能您正在寻找函数is_numeric()

http://php.net/manual/en/function.is-numeric.php

会告诉你字符串是否代表一个数字。