检查变量是否是PHP中的数字和正整数?

its*_*_me 1 php variables validation integer numbers

例如,说:

<?php

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

?>
Run Code Online (Sandbox Code Playgroud)

如何检查变量$post_id是否为数字,以及是否为正整数(即0-9,不是浮点数,分数或负数)?

编辑:不能使用is_int'因为$_GET返回一个字符串.认为我需要使用intval()或者ctype_digit(),后者看起来更合适.例如:

if( ctype_digit( $post_id ) ) { ... }
Run Code Online (Sandbox Code Playgroud)

mar*_*kli 5

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

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

  • 请记住,如果你的号码有浮点数即12.50,这将不起作用 (2认同)