PHP 字符串表征

PHP string characterization

我需要指定字符串类型是以 3 位数字、3 个字母还是组合开头。用户键入的字符串。

我的代码适用于字母和数字,但不适用于组合。我该怎么办?

 $type = substr($value, 0, 3);
 if(is_numeric($type)){
     echo 'starts with 3 digits';
 }elseif(is_string($type)){
     echo 'starts with 3 alphabetic characters';
 }else{
     echo 'undefined type?';
 }

您的函数调用可能 return 出乎意料的结果。我建议 ctype_ 呼吁可靠性:

$type = substr($value, 0, 3);
if(ctype_digit($type)){
    echo 'starts with 3 digits';
}elseif(ctype_alpha($type)){
    echo 'starts with 3 alphabetic characters';
}else{
    echo 'undefined type?';
}

p.s。如果要检查子串是否为字母和数字的组合,可以ctype_alnum().