处理用户输入时,验证数据以确保其完整性至关重要。一项常见的验证任务是检查变量是否表示整数。 PHP 为此提供了 is_int() 函数,但它可能并不总是能产生所需的结果。
使用 is_int() 可能会返回误报对于看起来是整数但函数无法识别的值。例如,考虑用户输入“1”作为页码的情况:
<code class="php">$page = $_GET['p'];</code>
在这种情况下,$page 将被分配字符串“1”,这将导致 is_int($page ) 返回 false。
要可靠地检查变量是否为整数,请考虑使用提供更准确结果的替代方法:
FILTER_VALIDATE_INT 过滤器可用于验证整数输入:
<code class="php">if (filter_var($page, FILTER_VALIDATE_INT) === false) { // Not an integer }</code>
输出:
TEST -1: -1 (type:integer) Your variable is an integer ✔ TEST 0 : 0 (type:integer) is an integer ✔ TEST 1 : 42 (type:integer) is an integer ✔ TEST 2 : 4.2 (type:double) is not an integer ✘ TEST 3 : 0.42 (type:double) is not an integer ✘ TEST 4 : 42 (type:double) is an integer ✔ TEST 5 : 42 (type:string) is an integer ✔ TEST 6 : a42 (type:string) is not an integer ✘ TEST 7 : 42a (type:string) is not an integer ✘ TEST 8 : 36 (type:integer) is an integer ✔ TEST 9 : 1337 (type:double) is an integer ✔
将变量的字符串表示形式与其整数表示形式进行比较也可以揭示它是否是整数:
<code class="php">if (strval($page) !== strval(intval($page))) { // Not an integer }</code>
输出:
TEST -1: -1 (type:integer) Your variable is an integer ✔ TEST 0 : 0 (type:integer) is an integer ✔ TEST 1 : 42 (type:integer) is an integer ✔ TEST 2 : 4.2 (type:double) is not an integer ✘ TEST 3 : 0.42 (type:double) is not an integer ✘ TEST 4 : 42 (type:double) is an integer ✔ TEST 5 : 42 (type:string) is an integer ✔ TEST 6 : a42 (type:string) is not an integer ✘ TEST 7 : 42a (type:string) is not an integer ✘ TEST 8 : 36 (type:integer) is an integer ✔ TEST 9 : 1337 (type:double) is an integer ✔
使用 ctype_digit 函数,可以检查正数和 0:
<code class="php">if (!ctype_digit(strval($page))) { // Not an integer }</code>
输出:
TEST -1: -1 (type:integer) # Your variable is not an integer ✘ TEST 0 : 0 (type:integer) is an integer ✔ TEST 1 : 42 (type:integer) is an integer ✔ TEST 2 : 4.2 (type:double) is not an integer ✘ TEST 3 : 0.42 (type:double) is not an integer ✘ TEST 4 : 42 (type:double) is an integer ✔ TEST 5 : 42 (type:string) is an integer ✔ TEST 6 : a42 (type:string) is not an integer ✘ TEST 7 : 42a (type:string) is not an integer ✘ TEST 8 : 36 (type:integer) is an integer ✔ TEST 9 : 1337 (type:double) is an integer ✔
正则表达式也可以用来验证整数:
<code class="php">if (!preg_match('/^-?\d+$/', $page)) { // Not an integer }</code>
输出:
TEST -1: -1 (type:integer) Your variable is an integer ✔ TEST 0 : 0 (type:integer) is an integer ✔ TEST 1 : 42 (type:integer) is an integer ✔ TEST 2 : 4.2 (type:double) is not an integer ✘ TEST 3 : 0.42 (type:double) is not an integer ✘ TEST 4 : 42 (type:double) is an integer ✔ TEST 5 : 42 (type:string) is an integer ✔ TEST 6 : a42 (type:string) is not an integer ✘ TEST 7 : 42a (type:string) is not an integer ✘ TEST 8 : 36 (type:integer) is an integer ✔ TEST 9 : 1337 (type:double) is an integer ✔
以上是如何可靠地检查 PHP 中的变量是否代表整数?的详细内容。更多信息请关注PHP中文网其他相关文章!