php 中文字符串截取的函数
2015-04-04 23:38
645 查看
//实现一个字符串截取的函数,类似于substr,必须能够截取中文这种多字节编码。假设每个中文也是一个字符,普通的数字、符号、字母也是一个字符。(提示:GB编码的中文 字符高位范围是 0x81-0xFE )
/*** 截取字符串子串 (1)(GBK)** @param string $str 原始字符串* @param int $len 需要截取字符串的长度* @return string 返回截取到的字符串*/function GBSubstr($str, $len){$count = 0;for($i=0; $i<strlen($str); $i++){if($count == $len) break;if(preg_match("/[\x80-\xff]/", substr($str, $i, 1))) ++$i;++$count;}return substr($str, 0, $i);}/*** 截取字符串子串函数(2)(GB)** @param string $src 源字符串* @param int $start 开始截取的位置* @param int $length 需要截取字符串的长度* @return string 返回截取的字符串*/function GBSubstr2($src, $start=0, $length=0){$suffix="";$len = strlen($src);if ( $len <= $length ) return $src;$cut_length = 0;for( $idx = 0; $idx<$length; $idx++){$char_value = ord($src[$idx]);if ( $char_value < 0x80 || ( $char_value & 0x40 ) )$cut_length++;else$cut_length = $cut_length + 3;}$curstr = substr($src, 0, $cut_length) ;preg_match('/^([\x00-\x7f]|.{3})*/', $curstr, $result);return $result[0];}/*** 中文字符串截取(3)(支持GB2312/GBK/UTF-8/BIG5)** @param string $str 要截取的字串* @param int $start 截取起始位置* @param int $length 截取长度* @param string $charset 字符串的字符集,包括有 utf-8|gb2312|gbk|big5 编码* @param bool $suffix 是否加尾缀* @return string 返回接续字符串的结果*/function CSubstr($str, $start=0, $length, $charset="gbk", $suffix=false){if(function_exists("mb_substr")){return mb_substr($str, $start, $length, $charset);}$re['utf-8'] = "/[\x01-\x7f]|[\xc2-\xdf][\x80-\xbf]|[\xe0-\xef][\x80-\xbf]{2}|[\xf0-\xff][\x80-\xbf]{3}/";$re['gb2312'] = "/[\x01-\x7f]|[\xb0-\xf7][\xa0-\xfe]/";$re['gbk'] = "/[\x01-\x7f]|[\x81-\xfe][\x40-\xfe]/";$re['big5'] = "/[\x01-\x7f]|[\x81-\xfe]([\x40-\x7e]|\xa1-\xfe])/";preg_match_all($re[$charset], $str, $match);$slice = join("", array_slice($match[0], $start, $length));if($suffix) {return $slice ."…";}return $slice;}
相关文章推荐
- php中的一个中文字符串截取函数
- PHP 中文字符串截取和翻转函数
- PHP 中文字符串截取无乱码的方法以及php汉字截取函数_preg_split()
- 多个PHP中文字符串截取函数
- PHP截取字符串,获取长度,获取字符位置的函数 中文字符截取
- php中的一个中文字符串截取函数
- 收藏几个支持中文的PHP字符串截取函数
- php 中文字符串截取函数-->比较好的
- 多个PHP中文字符串截取函数
- php中支持多种编码的中文字符串截取函数!
- php自动截取中文字符串 和 取出html、css、js格式函数
- 支持中文的PHP字符串截取函数 (附各语言的字符集编码范围)
- PHP中文字符串截取无乱码方法,php汉字截取函数_preg_split()
- php中计算中文字符串长度、截取中文字符串的函数代码
- php用正则表达式截取中文字符串的函数
- php截取中文字符串长度的mb_substr()、mb_strcut()函数 附strlen/mb_strlen
- php中计算中文字符串长度、截取中文字符串的函数代码
- 多个PHP中文字符串截取函数
- PHP中一个中文字符串截取函数
- php中高性能中文字符串截取函数分享