检查变量是否是PHP中的数字和正整数? [英] Check if variable is a number and positive integer in PHP?

查看:159
本文介绍了检查变量是否是PHP中的数字和正整数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

例如,说:

<?php

    // Grab the ID from URL, e.g. example.com/?p=123
    $post_id = $_GET['p'];

?>

如何检查变量 $ post_id 是一个数字,并且是一个正整数(即0-9,不是浮点数,分数或负数)?

How do I check if variable $post_id is a number, and a positive integer at that (i.e. 0-9, not a floating point number, fraction, or a negative number)?

编辑: 无法使用 is_int '原因 $ _ GET 返回一个字符串。我想我需要使用 intval() ctype_digit() ,后者似乎更合适。例如:

Can't use is_int 'cause $_GET returns a string. Think I need to use intval() or ctype_digit(), with the latter seeming more appropriate. For example:

if( ctype_digit( $post_id ) ) { ... }


推荐答案

要检查字符串输入是否为正整数,我总是使用函数ctype_digit 。这比正则表达式更容易理解和更快。

To check if a string input is a positive integer, i always use the function ctype_digit. This is much easier to understand and faster than a regular expression.

if (isset($_GET['p']) && ctype_digit($_GET['p']))
{
  // the get input contains a positive number and is safe
}

这篇关于检查变量是否是PHP中的数字和正整数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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