2012-10-25 20 views
-2

我知道is_int和ctype_digit和其他類似的,但我需要一個將返回true,並僅IF 價值ALL字符是數字。 ctype_digit將返回true,它使用科學記數法(5e4),以便不起作用。PHP函數只數字

必須返回true,如果:

123 
1.2 
-12 

如果有比上述以外的任何其他,將無法正常工作。

我強調這一點,因爲它似乎與所有那些在函數中建立的其中一個將能夠做到這一點。非常感謝你們!

+3

正則表達式的十進制

  • $結束後。 '/^- ?[0-9] * \。[0-9] * $ /'翻譯:開始時可選的'-',0或更多數字,可選'.',更多可選數字,結束。 –

  • +0

    @MichaelBerkowski你能說得更具描述性嗎? PS這個驗證在IF語句中(如果它有區別) –

    +0

    在'preg_match()'中使用它。之前已經問過這個問題,所以我正在尋找一個可靠的問題和可靠的答案。 –

    回答

    1

    你爲什麼不試試這個?

    function is_numbers($value){ 
        if(is_float($value)) return true; 
        if(is_int($value)) return true; 
    } 
    
    +2

    你最後需要一個'return false'語句。 – doublesharp

    +0

    如果值是「42」,這也不會返回true,因爲它在技術上是一個字符串。 – doublesharp

    +0

    @doublesharp:在這個問題中沒有,只能說在哪些情況下它必須返回TRUE。其他情況是未定義的(我說邏輯不是TRUE,NULL不是TRUE) – hakre

    0
    <?php 
        $tests = array("42",1337,"1e4","not numeric",array(),9.1); 
    
         foreach ($tests as $element) 
         { 
          if (is_numeric($element)) 
          { 
          echo "'{$element}' is numeric", PHP_EOL; 
          } 
          else 
          { 
          echo "'{$element}' is NOT numeric", PHP_EOL; 
          } 
    
         } 
        ?> 
    
    +0

    這個測試返回''1e4'是數字',這不是OP所要查找的。 – doublesharp

    0

    我不喜歡這東西來檢查純數字

    $var = (string) '123e4'; // number to test, cast to string if not already 
    $test1 = (int) $var; // will be int 123 
    $test2 = (string) $test1; // will be string '123' 
    
    if($test2 === $var){ 
        // no letters in digits of integer original, this time will fail 
        return true; 
    } 
    // try similar check for float by casting 
    
    return false; 
    
    0

    我無法找到恰好支持您需要回答的問題合適。我上面發佈的正則表達式將支持小數和負數。但是,它也支持前導零。如果你想消除這些,它會變得更復雜。

    $pattern = '/^-?[0-9]*\.?[0-9]*$/'; 
    
    echo preg_match($pattern, '-1.234') ? "match" : "nomatch"; 
    // match 
    echo preg_match($pattern, '-01.234') ? "match" : "nomatch"; 
    // match 
    echo preg_match($pattern, '1234') ? "match" : "nomatch"; 
    // match 
    echo preg_match($pattern, '001.234') ? "match" : "nomatch"; 
    // match (leading zeros) 
    echo preg_match($pattern, '-1 234') ? "match" : "nomatch"; 
    // nomatch (space) 
    echo preg_match($pattern, '-0') ? "match" : "nomatch"; 
    // match (though this is weird) 
    echo preg_match($pattern, '1e4') ? "match" : "nomatch"; 
    // nomatch (scientific) 
    

    打破格局:

    • ^啓動串
    • -?在字符串
    • [0-9]*的後跟零個或多個數字即將開始可選的負的
    • \.?後跟可選的小數點
    • [0-9]*和任選數字串