服务报价 | 域名主机 | 网络营销 | 软件工具| [加入收藏]
 热线电话: #
当前位置: 主页 > php教程 > php教程 >

解决PHP中substr产生的乱码,支持GB2312和UTF8两种编

时间:2016-03-18 09:24来源: 作者: 点击:
01 function jq_str( $title , $length ) 02 { 03 $encode = GB2312 ; //这里是文件使用的编码方式 这里只做GB2312和UTF8编码,根据系统使用的编码自行修改 04 if ( $encode == GB2312 ) 05 { 06 if ( strlen ( $title ) $le
01 function jq_str($title,$length)
02 {
03       $encode "GB2312"//这里是文件使用的编码方式 这里只做GB2312和UTF8编码,根据系统使用的编码自行修改
04       if($encode=="GB2312")
05       {
06             if (strlen($title)>$length)
07             {
08                   $temp = 0;
09                   for($i=0; $i<$length$i++)
10                   if (ord($title[$i])> 128) $temp++;
11                   if ($temp%2 == 0)
12                         $title substr($title,0,$length)."...";
13                   else
14                         $title substr($title,0,$length+1)."...";
15             }
16             return $title;
17       }
18       else if($encode=="utf-8")
19       {
20             $tmpTitle = preg_replace('#^(?:[\x00-\x7F]|[\xC0-\xFF][\x80-\xBF]+){0,0}'.
21 '((?:[\x00-\x7F]|[\xC0-\xFF][\x80-\xBF]+){0,'.$length.'}).*#s','$1',$title);
22             if(strlen($title)>$length)
23                   $tmpTitle .="...";
24             return $tmpTitle;
25       }
26  }

  函数其中的$encode变量可以修改为 GB2312和 utf-8两种,我只在这两种编码方式下进行了测试,如果是GBK编码用GB2312也应该可以,不过我没测试。

(责任编辑:最模板)
顶一下
(0)
0%
踩一下
(0)
0%
------分隔线----------------------------