2011-06-13 26 views
4

我遇到问题了。我正在删除一个txt文件并提取一个ID。问题是数据不一致,我必须评估数据。如何将字符串转换为整数并进行测试?

下面是一些代码:

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


if () { 

    echo "INTEGER"; 
} else{ 

    echo "STRING"; 
} 

我需要测试如果值$ A,$ B或者$ c是整数。这样做的最好方法是什么?我已经测试过“修剪”和使用“is_int”,但没有按预期工作。

有人能给我一些线索吗?

+0

作为你的数据在本例中的所有字符串使用时会显示错误is_int($ a)(或$ b或$ c) 你期待什么结果? $ a和$ b是真的吗?然后将其转换为int或使用is_numeric(),但请注意,使用科学记数法浮动,双精度和数字也将使用is_numeric()显示为true。 http://php.net/manual/en/function.is-numeric.php – billythekid 2011-06-13 11:10:18

回答

8

下面的例子甚至会工作,如果你的 “整数” 是一个字符串$a = "number";

is_numeric() 

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

intval($var) == $var 

或(同最后)

(int) $var == $var 
+0

-1是不是一个整数? – Piskvor 2011-06-13 11:09:24

+0

只有preg的例子不会验证-1。其他意愿。 – dynamic 2011-06-13 11:11:58

+1

@ yes123:[Integers](http://en.wikipedia.org/wiki/Integer)。请注意关于负数的部分 - OP没有指定“正整数”,是吗? ('/^- ?[0-9] + $ /'会起作用) – Piskvor 2011-06-13 11:15:13

1
<? 
$a = 34; 
if (is_int($a)) { 
    echo "is integer"; 
} else { 
    echo "is not an integer"; 
} 
?> 
$a="34"; 

不会验证为INT)

+0

不能工作,因为他有'$ a =“34”;' – dynamic 2011-06-13 11:11:47

+0

是的,我已经提到过它.. – Vamsi 2011-06-13 11:13:43

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.