PHP检测字符串是否以Alpha或Numeric

时间:2017-08-23 06:02:54

标签: php

我正在使用PHP从我的数据库中整理数据,并且需要知道字符串(varchar)值是以字母还是数字开头,所以我正在编写一个函数来检查它。

下面是我的代码,我得到了字符串的第一个字母,现在我的下一步是确定它的字母或数字,PHP可以实现吗?任何建议都会非常感谢!

function StartWith($str) {

     return  $str[0];

}

echo StartWith('AdamSavior');

4 个答案:

答案 0 :(得分:2)

更简单:

function StartWith($str)
{
    return is_numeric($str[0]) ? 'Number' : 'Letter';
}

echo StartWith('AdamSavior');

由于您的任务在数据库中,如果使用查询

,则会很好

答案 1 :(得分:2)

使用ctype_alphactype_digit函数的正确方法:

function startWith($str) {
    $c = $str[0];
    if (ctype_alpha($c)){
        return 'alpha';
    } else if (ctype_digit($c)){
        return 'numeric';
    } else {
        return 'other';
    }
}

echo startWith('AdamSavior') . PHP_EOL;
echo startWith('33man') . PHP_EOL;
echo startWith('---way') . PHP_EOL;

输出(连续):

alpha
numeric
other

答案 2 :(得分:0)

您可以使用is_numeric()函数。看看这个链接

How can I check if a char is a letter or a number?

答案 3 :(得分:0)

<?php

function StartWith($str)
{
    if(is_numeric($str[0])) {
        return "Number";

    }else{
        return "Letter";
    }
}
echo StartWith('adamSavior');
祝你好运!