要判断一个字符串是否全由数字组成,可以使用正则表达式或者内置函数is_numeric()来实现。
方法一:使用正则表达式
function isAllDigits($str) {
return preg_match('/^\d+$/', $str);
}
// 示例用法
$str1 = '123456'; // 全数字
$str2 = 'abc123'; // 包含字母
$str3 = '12.34'; // 包含小数点
if (isAllDigits($str1)) {
echo $str1 . '是全数字';
} else {
echo $str1 . '不是全数字';
}
if (isAllDigits($str2)) {
echo $str2 . '是全数字';
} else {
echo $str2 . '不是全数字';
}
if (isAllDigits($str3)) {
echo $str3 . '是全数字';
} else {
echo $str3 . '不是全数字';
}
方法二:使用内置函数is_numeric()
function isAllDigits($str) {
return is_numeric($str) && !strpos($str, '.');
}
// 示例用法
$str1 = '123456'; // 全数字
$str2 = 'abc123'; // 包含字母
$str3 = '12.34'; // 包含小数点
if (isAllDigits($str1)) {
echo $str1 . '是全数字';
} else {
echo $str1 . '不是全数字';
}
if (isAllDigits($str2)) {
echo $str2 . '是全数字';
} else {
echo $str2 . '不是全数字';
}
if (isAllDigits($str3)) {
echo $str3 . '是全数字';
} else {
echo $str3 . '不是全数字';
}
以上两种方法都可以判断一个字符串是否全由数字组成,根据实际情况选择使用其中一种方法即可。
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站