2011-06-13 62 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.