PHP函数只有数字

时间:2012-10-25 02:33:34

标签: php validation

我知道is_int和ctype_digit以及其他类似的东西,但我需要一个仅返回true且仅在 所有 值中的字符为数字的字符。 ctype_digit将返回true,你使用科学记数法(5e4),这样就无法使用了。

如果符合以下条件,则必须返回true:

123
1.2
-12

如果除上述内容之外的任何内容,将无法正常工作。

我强调这是因为看起来所有那些内置功能的人都可以做到这一点。非常感谢你们!

4 个答案:

答案 0 :(得分:1)

你为什么不尝试这个?

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

答案 1 :(得分: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;
          }

       }
    ?>

答案 2 :(得分: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;

答案 3 :(得分: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]*以及小数点后的数字
  • $字符串结尾
相关问题