PHP ctype_digit无法判断字符串是否为数字



>我有一个脚本,我想用它来处理来自客户端的用户输入。我有几项检查,但第一项要求提交的字符串为数字。

这是代码

<?php
$num = '09201x11222';
//Check whether the string is numeric
function test($str){
  return ctype_digit($str);
}
echo test($num);
echo '<br/><br/><br/>';
//Check if the length is exactly 10 characters
$len = strlen($num);
if($len < 10 || $len > 10){
  echo 'that number is wrong';
}
elseif($len == 10){
  echo 'that number is of required length';
}
echo '<br/><br/><br/>';
//Trim Leading Zero
$afterTrim = substr($num,1);
echo $afterTrim;
//Append countrycode 380 
echo '<br/><br/><br/>';
$countryCode = '380';
$afterAppend = $countryCode.$afterTrim;
echo $afterAppend;
?>

$num正确时,我在屏幕上得到 1,但当它错误时,我什么也得不到。为什么?

回显false将导致"无效"打印。 这是因为echo需要将布尔值转换为字符串表示形式。

从方法签名中可以看出

bool ctype_digit ( string $text )

这将返回一个由 echo 转换的布尔值:如果true,它将打印1,否则它将不打印任何内容。

从手册

布尔值 TRUE 将转换为字符串"1"。布尔值 FALSE 转换为 "(空字符串(。这允许在布尔值和字符串值之间来回转换。

最新更新