【问题标题】:How to convert a String to Integer and test it?如何将字符串转换为整数并进行测试?
【发布时间】:2011-06-13 11:02:27
【问题描述】:

我有问题。我正在报废一个 txt 文件并提取一个 ID。问题是数据不一致,我必须对数据进行评估。

这里有一些代码:

$a = "34";
$b = " 45";
$c = "ddd556z";


if (  ) {

    echo "INTEGER";
} else{ 

    echo "STRING";
}

我需要测试值 $a、$b 或 $c 是否为整数。这样做的最佳方法是什么?我已经测试过“修剪”和使用“is_int”,但没有按预期工作。

谁能给我一些线索?

【问题讨论】:

  • 因为你的数据在这个例子中都是字符串,你会在使用 is_int($a) (或 $b 或 $c)时显示 false 你期望什么结果? $a 和 $b 是真的吗?然后转换为 int 或使用 is_numeric() 但请注意,使用科学计数法的浮点数、双精度数和数字也将使用 is_numeric() 显示为 true。 php.net/manual/en/function.is-numeric.php

标签: php string integer type-conversion


【解决方案1】:

即使您的“int”是字符串$a = "number";,下面的示例也可以工作

is_numeric()

preg_match( '/^-?[0-9]+$/' , $var )  // negative number © Piskvor

intval($var) == $var

或(与上一个相同)

(int) $var == $var

【讨论】:

  • 只有带有 preg 的示例不会验证 -1。所有其他人都会。
  • @yes123:Integers。注意关于负数的部分 - OP没有指定“正整数”,是吗? (/^-?[0-9]+$/ 可以)
  • @piskvor:我写了 4 个例子。只有 preg 与负数不匹配。你认为给-1就足够了吗? ...无论如何,我已在答案中添加了您的解决方案。 +1 给你
  • @yes123:“我的部分答案是错误的,那又如何?”嗯,这绝对值得最大的负整数。
【解决方案2】:

http://www.php.net/manual/en/function.ctype-digit.php

<?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";
    }
}

// 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.

【讨论】:

    【解决方案3】:
    <?
    $a = 34;
    if (is_int($a)) {
        echo "is integer";
    } else {
        echo "is not an integer";
    }
    ?>
    
    $a="34";
    

    不会验证为 int ;)

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-11-20
      • 2010-10-13
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多