【问题标题】:How to check in PHP if a string can be transformed to integer?如果字符串可以转换为整数,如何检查 PHP?
【发布时间】:2011-08-02 16:25:13
【问题描述】:

我有以下形式的字符串:“37”、“42”、“7”。

我需要将它们转换为整数。我可以使用intval。但我想检查字符串是否采用预期的格式(我的意思是非预期格式,例如“abc”或“a7”)。在使用intval 之前或之后如何操作?

据我所知,intval 如果参数格式不正确,则返回 1。如果是这种情况,则无法仅通过分析 intval 的输出来检查参数是否是好的格式。

【问题讨论】:

  • 据我所知,如果参数格式不正确,intval 返回 1。 // 这是错误的。
  • intval("42istheans");/*42*/ intval("string") //0

标签: php string integer


【解决方案1】:

你可以使用

ctype_digit()

http://ro2.php.net/ctype_digit

【讨论】:

    【解决方案2】:

    您可能正在寻找filter_var

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

    您还可以将许多其他选项传递给此函数。我相信它被设计为一种验证表单提交的方式。

    【讨论】:

      【解决方案3】:

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

      【讨论】:

        【解决方案4】:

        您可以使用函数is_numeric()。如果是数字则返回 true,如果混合有字母则返回 false。

        【讨论】:

          【解决方案5】:

          平庸的解决方案,但你可以这样做:

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

          【讨论】:

            【解决方案6】:

            (int)$value == $value 怎么样?

            这会将值转换为 int,因此左手肯定是整数,然后检查无类型比较是否为真。

            【讨论】:

            • var_dump(((int)"xyz") == "xyz"); 返回真。现在=== 可能会起作用
            • (int)"xyz" 变为 0。然后,当您将 int 与字符串进行比较时,将字符串转换为 int。你真正建议的是 (int)"xyz" == (int)"xyz";
            猜你喜欢
            • 1970-01-01
            • 2016-10-07
            • 1970-01-01
            • 2010-12-28
            • 1970-01-01
            • 2022-10-15
            • 1970-01-01
            • 1970-01-01
            • 2022-09-30
            相关资源
            最近更新 更多