php 中对中英文混合字符串长度的判断及截取实例详解
7232708273 2023-1-25

/**
 * 
 * 中英混合字符串长度判断 
 * @param unknown_type $str
 * @param unknown_type $charset
 */
function strLength($str, $charset = 'utf-8') {
  if ($charset == 'utf-8')
    $str = iconv ( 'utf-8', 'gb2312', $str );
  $num = strlen ( $str );
  $cnNum = 0;
  for($i = 0; $i < $num; $i ++) {
    if (ord ( substr ( $str, $i + 1, 1 ) ) > 127) {
      $cnNum ++;
      $i ++;
    }
  }
  $enNum = $num - ($cnNum * 2);
  $number = ($enNum / 2) + $cnNum;
  return ceil ( $number );
}
/**
 * 
 * 中英混合的字符串截取
 * @param unknown_type $sourcestr
 * @param unknown_type $cutlength
 */
function cut_str($sourcestr, $cutlength) {
  $returnstr = '';
  $i = 0;
  $n = 0;
  $str_length = strlen ( $sourcestr ); //字符串的字节数 
  while ( ($n < $cutlength) and ($i <= $str_length) ) {
    $temp_str = substr ( $sourcestr, $i, 1 );
    $ascnum = Ord ( $temp_str ); //得到字符串中第$i位字符的ascii码 
    if ($ascnum >= 224) //如果ASCII位高与224,
    {
      $returnstr = $returnstr . substr ( $sourcestr, $i, 3 ); //根据UTF-8编码规范,将3个连续的字符计为单个字符   
      $i = $i + 3; //实际Byte计为3
      $n ++; //字串长度计1
    } elseif ($ascnum >= 192) //如果ASCII位高与192,
    {
      $returnstr = $returnstr . substr ( $sourcestr, $i, 2 ); //根据UTF-8编码规范,将2个连续的字符计为单个字符 
      $i = $i + 2; //实际Byte计为2
      $n ++; //字串长度计1
    } elseif ($ascnum >= 65 && $ascnum <= 90) //如果是大写字母,
    {
      $returnstr = $returnstr . substr ( $sourcestr, $i, 1 );
      $i = $i + 1; //实际的Byte数仍计1个
      $n ++; //但考虑整体美观,大写字母计成一个高位字符
    } else //其他情况下,包括小写字母和半角标点符号,
    {
      $returnstr = $returnstr . substr ( $sourcestr, $i, 1 );
      $i = $i + 1; //实际的Byte数计1个
      $n = $n + 0.5; //小写字母和半角标点等与半个高位字符宽...
    }
  }
  if ($str_length > $cutlength) {
    $returnstr = $returnstr . "..."; //超过长度时在尾处加上省略号
  }
  return $returnstr;
}

奇狐首页

最新回复 (3)
全部楼主
  • stl176
    2023-1-26 2
    0
    沙发我没有,板凳我没有,板也没有,只好站在后面排队支持! 
  • a15174
    2023-1-27 3
    0
    楼主,我只是来混个熟的!老板,侬亿雷凑闹嫩了!
  • Kuai
    5月前 4
    0
    我要拿出这帖子奉献给世人赏阅,我要把这个帖子一直往上顶,往上顶!顶到所有人都看到为止! 
返回