PHP中的一个ctype_digit()函数,用于检查文本的每个字符是否为数字。如果字符串的所有字符都是数字,则返回TRUE,否则返回FALSE。
null
语法:
ctype_digit(string text)
使用的参数: PHP中的ctype_digit()函数只接受一个参数。
- 文本: 它的强制参数指定了被测试的字符串。
返回值: 如果字符串的所有字符都是数字,则返回TRUE,否则返回FALSE。
错误和例外:
- 传递字符串时给出预期结果,传递整数时不给出预期输出。
- 该函数在PHP 5.1.0以前版本的空字符串上返回true
例如:
Input :789495001 Output : Yes Explanation : All digits, return True Input : 789.0877 Output : No Explanation: String contains floating point, return false.
下面的程序演示了ctype_digit()函数。
课程:1 正在检查包含所有数字的单个字符串的ctype_digit()函数。
<?php // PHP program to check given string is // control character $string = '123456789' ; // Checking above given string // by using of ctype_digit() function. if ( ctype_digit( $string )) { // if true then return Yes echo "Yes" ; } else { // if False then return No echo "No" ; } ?> |
输出:
Yes
课程:2 驱动一个代码ctype_digit()函数,其中的输入将是包含特殊字符、整数和字符串的字符串数组。
<?php // PHP program to check is given string // contains all digits using ctype_digit $strings = array ( 'Geeks-2018' , 'geek@yahoo.com' , '10.99999Fe' , '12345' , 'geeksforgeeks.org' ); // Checking above given strings //by used of ctype_digit() function . foreach ( $strings as $testcase ) { if (ctype_digit( $testcase )) { // if true then return Yes echo "Yes" ; } else { // if False then return No echo "No" ; } } ?> |
输出:
No No No Yes No
ctype_digit()vs is_int() ctype_digit()基本上代表字符串类型,而对于整数类型则是_int()。ctype_digit()遍历所有字符并检查每个字符是否为数字。例如
<?php // PHP code to demonstrate difference between // ctype_digit() and is_int(). $x = "-123" ; if (ctype_digit( $x )) echo "Yes" ; else echo "No" ; $x = -123; if ( is_int ( $x )) echo "Yes" ; else echo "No" ; ?> |
输出:
No Yes
参考资料: http://php.net/manual/en/function.ctype-digit.php
© 版权声明
文章版权归作者所有,未经允许请勿转载。
THE END