PHP:检查输入是否为有效数字的最佳方法? [英] PHP: Best way to check if input is a valid number?

查看:95
本文介绍了PHP:检查输入是否为有效数字的最佳方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

检查输入是否为数字的最佳方法是什么?

What is the best way of checking if input is numeric?

  • 1-
  • +111 +
  • 5xf
  • 0xf

这类数字无效.只有数字,例如:123、012(12),正数才有效. 这是mye当前代码:

Those kind of numbers should not be valid. Only numbers like: 123, 012 (12), positive numbers should be valid. This is mye current code:

$num = (int) $val;
if (
    preg_match('/^\d+$/', $num)
    &&
    strval(intval($num)) == strval($num)
    )
{
    return true;
}
else
{
    return false;
}

推荐答案

ctype_digit 正是为此目的而构建的目的.

ctype_digit was built precisely for this purpose.

这篇关于PHP:检查输入是否为有效数字的最佳方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆