【问题标题】:How can one check in PHP if a string can be converted into a whole number?如果可以将字符串转换为整数,如何检查 PHP?
【发布时间】:2012-02-24 04:07:42
【问题描述】:

例如“000”、“404”和“0523”在PHP中可以转换为整数,但“42sw”和“423 2343”不能转换为整数。

【问题讨论】:

标签: php


【解决方案1】:

42Sw 可以使用 intval() 转换为数字

      echo intval("42sW"); // prints 42

【讨论】:

    【解决方案2】:

    你可以试试这样的。

    <?php
    if (is_numeric($string)) {
    //functions here
    }
    else{
    //functions2 here
    }
    ?>
    

    【讨论】:

    • 这对于像 '1.5' 这样的东西是正确的
    【解决方案3】:

    ctype_digit 应该是您要查找的内容。

    【讨论】:

      【解决方案4】:

      使用ctype_digit 函数。 is_numeric 也将允许浮点值。

      $numArray = array("1.23","156", "143", "1w");
      foreach($numArray as $num)
      {
          if (ctype_digit($num)) {
                  // Your Convert logic
              } else {
                  // Do not convert print error message
              }
          }
      }
      

      【讨论】:

      • 谢谢,ctype_digit 效果很好。 is_numeric 不起作用,因为所有有理数都适用于 is_numeric,但也很高兴知道该函数,谢谢!
      • @gus 你想说什么。
      • 如果你传入 int ,不管它是一个整数,它都会返回 false 。这可能不是预期的。觉得值得一提,干杯。
      • $numArray = array("1.23",156, "143", "1w"); 1.23 假 156 假 143 真 1w 假
      • @David Faux:1.2e2 是一个“整数”,但将无法通过 ctype,_digit() 测试。
      【解决方案5】:

      PHP 的is_numeric() 可以确定给定参数是数字还是数字字符串。阅读manual 中的一些示例。

      【讨论】:

      • 这对于像 '1.5' 这样的东西是正确的
      【解决方案6】:

      使用is_numeric():

      if (is_numeric("string")) {
          echo "This can be converted to a number";
      }
      

      【讨论】:

      • 这对于像 '1.5' 这样的东西是正确的
      【解决方案7】:
      $test = "42sW"; if (ctype_digit($test)) { echo "The string $test consists of all digits.\n"; } else { echo "The string $test does not consist of all digits.\n"; } //OR is_numeric($test); // false

      【讨论】:

      • is_numeric() 不会对非整数 (1.23) 也返回 true 吗?
      猜你喜欢
      • 1970-01-01
      • 2016-10-07
      • 1970-01-01
      • 1970-01-01
      • 2010-12-28
      • 2010-10-13
      • 1970-01-01
      相关资源
      最近更新 更多