本文章提供这三款php 截取字符串函数各有各的特点,所有字符串截取函数都支持中文汉字截取,解决了乱码问题,方法二,支持多种编码的截取.
字符串截取函数一,代码如下:
- function mystr($str,$str_len) {
- if (strlen($str)<=$str_len) {
- return $str;
- }else return mysubstr($str,0,$str_len)."...";
- }
- function mysubstr($str, $start, $len) {
- $tmpstr = "";
- $strlen = $start + $len;
- for($i = 0; $i < $strlen; $i++) {
- if(ord(substr($str, $i, 1)) > 0xa0) {
- $tmpstr .= substr($str, $i, 2);
- $i++;
- } else
- $tmpstr .= substr($str, $i, 1);
- }
- return $tmpstr;
- }
字符截取函数二,代码如下:
- function syssubstr($string,$length,$append = false)
- {
- if (strlen($string) < = $length )
- {
- return $string;
- }
- else
- {
- $i = 0;
- while ($i < $length)
- {
- $stringtmp = substr($string,$i,1);
- if ( ord($stringtmp) >=224 )
- {
- $stringtmp = substr($string,$i,3);
- $i = $i + 3;
- }
- elseif( ord($stringtmp) >=192 )
- {
- $stringtmp = substr($string,$i,2);
- $i = $i + 2;
- }
- else
- {
- $i = $i + 1;
- }
- $stringlast[] = $stringtmp;
- }
- $stringlast = implode("",$stringlast);
- if($append)
- {
- $stringlast .= "...";
- }
- return $stringlast;
- }
- }
-
- $string = "";
- $length = "18";
- $append = false;
- echo syssubstr($string,$length,$append);
utf-8:$byte=3 | gb 2312:$byte=2 | big5:$byte=2,代码如下:
- function bite_str($string, $start, $len, $byte=3)
- {
- $str = "";
- $count = 1;
- $str_len = strlen($string);
- for ($i=0; $i<$str_len; $i++) {
- if (($count+1-$start)>$len) {
- $str .= "...";
- break;
- } elseif ((ord(substr($string,$i,1)) <= 128) && ($count < $start)) {
- $count++;
- } elseif ((ord(substr($string,$i,1)) > 128) && ($count < $start)) {
- $count = $count+2;
- $i = $i+$byte-1;
- } elseif ((ord(substr($string,$i,1)) <= 128) && ($count >= $start)) {
- $str .= substr($string,$i,1);
- $count++;
- } elseif ((ord(substr($string,$i,1)) > 128) && ($count >= $start)) {
- $str .= substr($string,$i,$byte);
- $count = $count+2;
- $i = $i+$byte-1;
- }
- }
- return $str;
- }
-
-
- $str = "1测试测试2测试测试3测试测试4测试测试";
- echo $str;
- echo "<br>".bite_str($str,0,20,2);
方法四,支持中英文字符串截取函数,代码如下:
- function ccstrlen($str) #计算中英文混合字符串的长度
- {
- $cclen=0;
- $asclen=strlen($str);
- $ind=0;
- $hascc=ereg("[xa1-xfe]",$str); #判断是否有汉字
- $hasasc=ereg("[x01-xa0]",$str); #判断是否有ascii字符
- if($hascc && !$hasasc) #只有汉字的情况
- return strlen($str)/2;
- if(!$hascc && $hasasc) #只有ascii字符的情况
- return strlen($str);
- for($ind=0;$ind<$asclen;$ind++)
- {
- if(ord(substr($str,$ind,1))>0xa0)
- {
- $cclen++;
- $ind++;
- }
- else
- {
- $cclen++;
- }
- }
- return $cclen;
- }
|