【问题标题】:PHP detect if string starts with Alpha or Numeric [duplicate]PHP检测字符串是否以字母或数字开头[重复]
【发布时间】:2018-01-31 13:45:58
【问题描述】:

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

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

function StartWith($str) {

     return  $str[0];

}

echo StartWith('AdamSavior');

【问题讨论】:

标签: php


【解决方案1】:

使用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

【讨论】:

  • 哇,谢谢other 是一个奖励,如果它以特殊字符开头,我也在考虑获得。
  • @KaoriYui,不客气
【解决方案2】:

为了更简单:

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

echo StartWith('AdamSavior');

由于您的任务在数据库中,如果使用查询完成会很好

【讨论】:

    【解决方案3】:

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

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

    【讨论】:

      【解决方案4】:
      <?php
      
      function StartWith($str)
      {
          if(is_numeric($str[0])) {
              return "Number";
      
          }else{
              return "Letter";
          }
      }
      echo StartWith('adamSavior');
      

      祝你好运!

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2023-01-01
        • 2012-03-22
        • 2017-02-27
        • 2014-01-15
        • 2013-09-04
        • 2013-06-01
        • 1970-01-01
        相关资源
        最近更新 更多