(PHP 4 >= 4.0.4, PHP 5, PHP 7, PHP 8)
ctype_digit — 做純數字檢測
$text
): bool
檢查提供的 string 和 text
里面的字符是不是都是數字。
text
需要被測試的字符串。
如果 text
字符串是一個(gè)十進(jìn)制數字,就返回 true
;反之就返回 false
。
版本 | 說(shuō)明 |
---|---|
5.1.0 |
在 PHP 5.1.0 之前,當 text 是一個(gè)空字符串的時(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)比對字符和整數的例子。
<?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è)函數的參數要求是一個(gè) string 這一點(diǎn)是非常有用的,因此當你傳入一個(gè) integer 的參數也許不能得到期望的結果。然后,同樣需要注意HTML表單將會(huì )返回數字字符串而不是一個(gè)整型。 看下手冊的 types 章節。
注意:
如果給出一個(gè) -128 到 255 之間(含)的int, 將會(huì )被解釋為該值對應的ASCII字符 (負值將加上 256 以支持擴展ASCII字符). 其它整數將會(huì )被解釋為該值對應的十進(jìn)制字符串.