PHP Conference Japan 2024

ctype_xdigit

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

ctype_xdigit 檢查字元是否代表十六進位數字

說明

ctype_xdigit(混合 $text): 布林值

檢查提供的 字串 text 中的所有字元是否都是十六進位「數字」。

參數

text

要測試的字串。

注意事項:

如果提供介於 -128 和 255 之間(含)的 整數,它會被解釋為單個字元的 ASCII 值(負值會加上 256,以便允許擴展 ASCII 範圍內的字元)。任何其他整數都會被解釋為包含整數十進位數字的字串。

警告

從 PHP 8.1.0 開始,不建議傳遞非字串參數。將來,該參數將被解釋為字串,而不是 ASCII 字碼點。根據預期的行為,應將參數強制轉換為 字串 或明確呼叫 chr() 函式。

返回值

如果 text 中的每個字元都是十六進位「數字」,即十進位數字或 [A-Fa-f] 範圍內的字元,則返回 true,否則返回 false。當使用空字串呼叫時,結果將始終為 false

範例

範例 #1 ctype_xdigit() 範例

<?php
$strings
= array('AB10BC99', 'AR1012', 'ab12bc99');
foreach (
$strings as $testcase) {
if (
ctype_xdigit($testcase)) {
echo
"字串 $testcase 包含全十六進位數字。\n";
} else {
echo
"字串 $testcase 並非全由十六進位數字組成。\n";
}
}
?>

以上範例將輸出:

The string AB10BC99 consists of all hexadecimal digits.
The string AR1012 does not consist of all hexadecimal digits.
The string ab12bc99 consists of all hexadecimal digits.

另請參閱

新增註釋

使用者貢獻的註釋 1 則註釋

tom at hgmail dot com
18 年前
當網站要求使用者輸入十六進位顏色碼時,這個函式就顯得很有用。它可以防止使用者輸入「neon-green」或錯誤的程式碼類型,例如 355511235,從而避免違反 W3C 標準。

結合 strlen(),您可以建立如下函式:

function check_valid_colorhex($colorCode) {
// 如果使用者不小心傳入了 # 符號,則將其移除
$colorCode = ltrim($colorCode, '#');

if (
ctype_xdigit($colorCode) &&
(strlen($colorCode) == 6 || strlen($colorCode) == 3))
return true;

否則回傳 false;
}
To Top