2011-04-03 90 views
4

我不知道如何處理這個問題,我試過什麼對我來說是最明顯的解決方案,但到目前爲止沒有任何證據表明它完全令人滿意。我必須俯視一些非常簡單的事情。如何在PHP中驗證未簽名的數字?

我有一個文本類型的輸入形式:

<input type="text" name="album_id"> 

我想驗證輸入,因此用戶只能進入無符號整數...

$required = array(); // required or invalid input 

$tmp = trim($_POST['album_id']); 

if (!is_int((int)$tmp)) { 
    $required['album'] = 'The album id must contain a positive numeric value only.'; 
} 

到目前爲止我使用!is_numeric($tmp)但用戶可以輸入9.2或'1e4',它會驗證...所以一個不起作用。

我也試過!is_int((int)$tmp)但由於某種原因,那一個不工作(也許它應該,但我做錯了......)。 我試過ctype_digit沒有成功。 我可能忽略了一些東西,但不知道是什麼。

如何驗證在php中的無符號數字?沒有浮點數,負數等...只有一個簡單的無符號數(1到n)。

回答

7

如果你想檢查是否存在變量只包含數字(這似乎是你想要的東西,在這裏),你可能必須去與ctype_digit()


不知道你嘗試過什麼,但這樣的事情應該工作:

$tmp = trim($_POST['album_id']); 
if (ctype_digit($tmp)) { 
    // $tmp only contains digits 
} 
+0

確實......我已經把NOT這個符號放在這裏!ctype_digit($ tmp),它似乎可以正常工作!當它顯示$ integer = 42時,我認爲文檔讓我失望; //假我忘記輸入是一個字符串默認情況下不是一個整數....謝謝 – Marco 2011-04-03 10:40:59

+0

那麼,很高興我能幫助:-) – 2011-04-03 10:43:11

1

你可以使用preg_match()

if(preg_match('/^[\\d+]$/', $tmp) == 0) 
    $required['album'] = 'The album id must ...'; 

請注意,這不會做了積極的範圍檢查(例如獲得更大的整數的最大有效值)。

編輯: 使用Pascal MARTIN的解決方案,除非您想進行更復雜的檢查(例如需要其他特殊字符),因爲我猜想它提供了更好的性能用於此用途。

1
if (preg_match('!^[1-9][0-9]*$!',$tmp)) { 
+0

「0」 和類似 「0123」 仍然是有效的整數值。我不會認爲任何人會希望這些數字被認爲是八進制數。 – Mario 2011-04-03 10:33:55

4

filter_var()功能是這裏的工作的工具。

這裏有一個過濾器,將返回非假只爲無符號整數或無符號整數,字符串:

$filteredVal = filter_var($inputVal, 
          FILTER_VALIDATE_INT, 
          array('options' => array('min_range' => 0))); 

這裏的documentation on filters

實施例:

<?php 

$testInput = array(
      "zero string" => "0", 
      "zero" => 0, 
      "int" => 111, 
      "string decimal" => "222", 
      "empty string" => "", 
      "false" => false, 
      "negative int" => -333, 
      "negative string decimal" => "-444", 
      "string octal" => "0555", 
      "string hex" => "0x666", 
      "float" => 0.777, 
      "string float" => "0.888", 
      "string" => "nine" 
     ); 

foreach ($testInput as $case => $inputVal) 
{ 
    $filteredVal = filter_var($inputVal, 
           FILTER_VALIDATE_INT, 
           array('options' => array('min_range' => 0))); 

    if (false === $filteredVal) 
    { 
     print "$case (". var_export($inputVal, true) . ") fails\n"; 
    } 
    else 
    { 
     print "$case (". var_export($filteredVal, true) . ") passes\n"; 
    } 
} 

輸出:

zero string (0) passes 
zero (0) passes 
int (111) passes 
string decimal (222) passes 
empty string ('') fails 
false (false) fails 
negative int (-333) fails 
negative string decimal ('-444') fails 
string octal ('0555') fails 
string hex ('0x666') fails 
float (0.777) fails 
string float ('0.888') fails 
string ('nine') fails 
+0

要小心32位限制:2147483647通過檢查「整數> 0」。 2147483648失敗。添加引號似乎沒有任何幫助。 – 2015-03-25 20:17:07