• 0
  • 0

检测用户名时候包含中文以及限制长度

2021-02-19 359 0 admin 所属分类:PHP 记录
/***
* @param string $username 用户名  数据库char字段为 15 允许存储最多15个字符 包括汉字
*/
public function check_name_length($username = '')
{
  $length = mb_strlen($username, 'UTF-8');

  $preg = "/[\x{4e00}-\x{9fa5}]+/u";
  if (preg_match_all($preg, $username, $matches)) {
      //特殊需求 限定 中文字符最多6个
      $chinese_length = mb_strlen(implode("", $matches[0]), "UTF-8");
      if ($chinese_length > 6) {
          fail("最多支持6个中文字符");
      }
  }

  if ($length > 16) {
      fail("用户名超出长度限制");
  }

  if ($length < 3) {
      fail("用户名最短不能小于4位");
  }
}


返回顶部