

一些不常用的PHP字符类型检测函数
source link: https://hxd.life/2021/02/21/%E4%B8%80%E4%BA%9B%E4%B8%8D%E5%B8%B8%E7%94%A8%E7%9A%84PHP%E5%AD%97%E7%AC%A6%E7%B1%BB%E5%9E%8B%E6%A3%80%E6%B5%8B%E5%87%BD%E6%95%B0/
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

主要是 Ctype 扩展所提供的函数,用来检测在当前的区域设定下,一个字符或者字符串,是否仅包含指定类型的字符。此类函数用来替代简单的正则验证,效率高于正则验证。参数为字符串,如果给出一个 -128 到 255 之间(含)的 int, 将会被解释为该值对应的 ASCII 字符 (负值将加上 256 以支持扩展 ASCII 字符). 其它整数将会被解释为该值对应的十进制字符串。
Ctype 系列函数
- ctype_alnum — 做字母和数字字符检测,仅包含 [A-Za-z0-9] 返回 true
- ctype_alpha — 做纯字符检测,仅包含 [A-Za-z] 返回 true
- ctype_cntrl — 做控制字符检测,\r \t \n 为控制字符,仅包含控制字符才返回 true
- ctype_digit — 做纯数字检测,请看下面额外说明
- ctype_graph — 做可打印字符串检测,空格除外,测试显示包含 \r \t \n 会返回 false,’asdf ‘ 同样会返回 false
- ctype_lower — 做小写字符检测
- ctype_print — 做可打印字符检测 ‘asdf ‘ 字符串会返回 true
- ctype_punct — 检测可打印的字符是不是不包含空白、数字和字母,其实就是全都是标点符号才返回 true,其他返回 false
- ctype_space — 做空白字符检测,必须全为 ‘ ‘ 空字符串才返回 true,其他返回 false
- ctype_upper — 做大写字母检测
- ctype_xdigit — 检测字符串是否只包含十六进制字符,即只能包含十进制的树枝和 [A-Fa-f] 的字母,否则返回 false
这个函数的参数要求是一个 string 这一点是非常有用的,因此当你传入一个 integer 的参数也许不能得到期望的结果。
$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";
}
}
// 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.
第二个示例:直接传入整型数字被转成 ASCII 码处理了
$numeric_string = '42';
$integer = 42;
ctype_digit($numeric_string); // true
ctype_digit($integer); // false (ASCII 42 是 * 字符)
is_numeric($numeric_string); // true
is_numeric($integer); // true
ctype_digit(255) // false
ctype_digit(256) // true
参考链接:PHP 字符类型检测
最后恰饭 阿里云全系列产品/短信包特惠购买 中小企业上云最佳选择 阿里云内部优惠券
Recommend
About Joyk
Aggregate valuable and interesting links.
Joyk means Joy of geeK