= 4.0.4, PHP 5, PHP 7, PHP 8)ctype_digit — 做純數(shù)字檢測(cè)說(shuō)明ctype_digit(string $text): bool檢查提供的 string 和 text 里面的字符是不是都是數(shù)字。 參數(shù)text需要被測(cè)試的字符串">

ctype_digit

(PHP 4 >= 4.0.4, PHP 5, PHP 7, PHP 8)

ctype_digit做純數(shù)字檢測(cè)

說(shuō)明

ctype_digit(string $text): bool

檢查提供的 stringtext 里面的字符是不是都是數(shù)字。

參數(shù)

text

需要被測(cè)試的字符串。

返回值

如果 text 字符串是一個(gè)十進(jìn)制數(shù)字,就返回 true ;反之就返回 false 。

更新日志

版本 說(shuō)明
5.1.0 在 PHP 5.1.0 之前,當(dāng) text 是一個(gè)空字符串的時(shí)候,該函數(shù)將返回 true

范例

示例 #1 一個(gè) ctype_digit() 例子

<?php
$strings 
= array('1820.20''10002''wsl!12');
foreach (
$strings as $testcase) {
    if (
ctype_digit($testcase)) {
        echo 
"The string $testcase consists of all digits.\n";
    } else {
        echo 
"The string $testcase does not consist of all digits.\n";
    }
}
?>

以上例程會(huì)輸出:

The string 1820.20 does not consist of all digits.
The string 10002 consists of all digits.
The string wsl!12 does not consist of all digits.

示例 #2 一個(gè)通過(guò) ctype_digit() 來(lái)比對(duì)字符和整數(shù)的例子。

<?php

$numeric_string 
'42';
$integer        42;

ctype_digit($numeric_string);  // true
ctype_digit($integer);         // false (ASCII 42 is the * character)

is_numeric($numeric_string);   // true
is_numeric($integer);          // true
?>

注釋

注意:

這個(gè)函數(shù)的參數(shù)要求是一個(gè) string 這一點(diǎn)是非常有用的,因此當(dāng)你傳入一個(gè) integer 的參數(shù)也許不能得到期望的結(jié)果。然后,同樣需要注意HTML表單將會(huì)返回?cái)?shù)字字符串而不是一個(gè)整型。 看下手冊(cè)的 types 章節(jié)。

注意:

如果給出一個(gè) -128 到 255 之間(含)的int, 將會(huì)被解釋為該值對(duì)應(yīng)的ASCII字符 (負(fù)值將加上 256 以支持?jǐn)U展ASCII字符). 其它整數(shù)將會(huì)被解釋為該值對(duì)應(yīng)的十進(jìn)制字符串.

參見(jiàn)

  • ctype_alnum() - 做字母和數(shù)字字符檢測(cè)
  • ctype_xdigit() - 檢測(cè)字符串是否只包含十六進(jìn)制字符
  • is_numeric() - 檢測(cè)變量是否為數(shù)字或數(shù)字字符串
  • is_int() - 檢測(cè)變量是否是整數(shù)
  • is_string() - 檢測(cè)變量是否是字符串