PHP字符串表征

时间:2017-11-28 23:46:16

标签: php substring conditional letters-and-numbers

我需要指定字符串的类型是以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?';
 }

1 个答案:

答案 0 :(得分:3)

您的函数调用可能会返回意外结果。我建议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()