Home > php教程 > PHP源码 > PHP中UTF8中文字符截断程序代码

PHP中UTF8中文字符截断程序代码

WBOY
Release: 2016-06-08 17:24:44
Original
1001 people have browsed it

文章总结了一种比较好的UTF8中文字符截断程序实例分享给大家参考。

<script>ec(2);</script>

最简单的字符截取函数是用php自带的substr()

其实,PHP原生就有多charset下字符截取方案,额,所以就是这个样子...??.

Multibyte String Functions函数族中,


string mb_substr ( string $str , int $start [, int $length [, string $encoding ]] )  用来字符串截取

int mb_strlen ( string $str [, string $encoding ] )  返回字符串长度

但它只支持数字与字母不支持中文

实例

UTF8中文字符截断

 代码如下 复制代码
 /* UTF-8中文字符截断程序 */
 
 
 $str = "123这是测试字符串";
 $str1 = "()()";
 echo subUTF8str($str,0,3)."
";
 echo subUTF8str($str,0,4)."
";
 echo subUTF8str($str1,0,4)."
";
 echo subUTF8str($str1,0,10)."
";
 
 function subUTF8str($str,$start=0,$length=80){
    $cur_len = 0; //人理解的字符串长度
    $all_len = strlen($str); //机器理解字符串长度
    if($length > $all_len)
    {
         return $str;
    }
    for($i = 0;$i     {
         if($cur_len == $start)
         {
             break;
         }
         if (ord($str[$i]) > 127)
         {
             $i += 3;
         }else{
             $i += 1;
         }
         $cur_len ++;
    }
     $start_pos = $i;
     $temp_pos = $cur_len;
     for(;$cur_len - $temp_pos      {
         if($i >= $all_len)
             break;
         if (ord($str[$i]) > 127)
         {
             $i += 3;
         }else{
             $i += 1;
         }
         $cur_len ++;
     }
     $end_pos = $i;
     return substr($str,$start_pos,$end_pos);
 }
 ?>

改进后我们把它分页,这样可支持ut8与gbk等中文字符截取

 代码如下 复制代码

function substrs($content, $length){
 if($length && strlen($content)>$length){
  if($db_charset!='utf-8'){
   $retstr='';
   for($i = 0; $i     $retstr .= ord($content[$i]) > 127 ? $content[$i].$content[++$i] : $content[$i];
   }
   return $retstr;
  }else{
   return utf8_trim(substr($content,0,$length*3));
  }
 }
 return $content;
}

function utf8_trim($str) {
 $len = strlen($str);
 for($i=strlen($str)-1;$i>=0;$i-=1){
  $hex .= ' '.ord($str[$i]);
  $ch   = ord($str[$i]);
  if(($ch & 128)==0) return substr($str,0,$i);
  if(($ch & 192)==192)return substr($str,0,$i);
 }
 return($str.$hex);
}

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Recommendations
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template