UTF-8、GB2312都支持的汉字截取函数

添加时间:13-07-05 所属分类:PHP工具与代码
  转载自http://www.jb51.net/article/4999.htm

[code]<?php
/*
Utf-8、gb2312都支持的汉字截取函数
cut_str(字符串, 截取长度, 开始长度, 编码);
编码默认为 utf-8
开始长度默认为 0
*/function cut_str($string, $sublen, $start = 0, $code = 'UTF-8')
{
if($code == 'UTF-8')
{
$pa ="/[\x01-\x7f]|[\xc2-\xdf][\x80-\xbf]|\xe0[\xa0-\xbf][\x80-\xbf]|[\xe1-\xef][\x80-\xbf][\x80-\xbf]|\xf0[\x90-\xbf][\x80-\xbf][\x80-\xbf]|[\xf1-\xf7][\x80-\xbf][\x80-\xbf][\x80-\xbf]/";
preg_match_all($pa, $string, $t_string); if(count($t_string[0]) - $start > $sublen) return join('', array_slice($t_string[0], $start, $sublen))."...";
return join('', array_slice($t_string[0], $start, $sublen));
}
else
{
$start = $start*2;
$sublen = $sublen*2;
$strlen = strlen($string);
$tmpstr = ''; for($i=0; $i<$strlen; $i++)
{
if($i>=$start && $i<($start+$sublen))
{
if(ord(substr($string, $i, 1))>129)
{
$tmpstr.= substr($string, $i, 2);
}
else
{
$tmpstr.= substr($string, $i, 1);
}
}
if(ord(substr($string, $i, 1))>129) $i++;
}
if(strlen($tmpstr)<$strlen ) $tmpstr.= "...";
return $tmpstr;
}
}$str = "abcd需要截取的字符串";
echo cut_str($str, 8, 0, 'gb2312');
?> [/code]

前篇:三个“夜游济南”套餐推出 趵突泉门票半价出... 后篇:一篇入门的php Class 文章
发表我的评论


推荐文章   寻找最美孝心少年 央视被济南孩子的“别...   无臂大学生用双脚打游戏   最励志的直播 街头“脚书”引围观   济南老鞋匠5年做了100多只微型鞋 最小的...   济南辅警“飙”英语教育闯红灯老外 业余...
随机文章   php 用iconv()函数 解UNICODE编码 UTF-...   php 用iconv()函数 将Unicode编码转换成...   PHP加解密迅雷,flashget快车,QQ旋风地...   PHP去除字符串尾部空格和小数点   PHP的简单文字过滤函数
广告

其他推荐

因为本站所有内容均转载自其它媒体,本意为公众提供免费服务,但并不代表本网赞同其观点,也不能对其真实性验证负责,如稿件版权单位或个人不想在本网发布,请与我联系,本人会立即将其撤除,谢谢.联系方式:atseashawk@163.com QQ:99289555