用这种方式基本没乱码出现
还支持不同的编码过来的字符串
比一般的截取函数简单多了
/**
* 字符串截取
*
* @param string $str 要截取字符串
* @param int $len 截取长度
* @param string $prefix 补充字符,如果截取了,则补充一个字符到后面,截取长度不包含这部分
* @param string $charset 编码
*
* @return string 截取后的字符串
*/
function cut_str_cn ($str , $len , $prefix='...' , $charset='utf-8')
{
/* 定义字符集 */
$arr['utf-8'] = "/[/x01-/x7f]|[/xc2-/xdf][/x80-/xbf]|[/xe0-/xef][/x80-/xbf]{2}|[/xf0-/xff][/x80-/xbf]{3}/";
$arr['gb2312'] = "/[/x01-/x7f]|[/xb0-/xf7][/xa0-/xfe]/";
$arr['gbk'] = "/[/x01-/x7f]|[/x81-/xfe][/x40-/xfe]/";
$arr['big5'] = "/[/x01-/x7f]|[/x81-/xfe]([/x40-/x7e]|/xa1-/xfe])/";
/* 字符放到数组内 */
preg_match_all($arr[$charset], $str, $match);
/* 截取 */
$result = implode("",array_slice($match[0], 0, $len));
return $length<count($match[0])?($result.$prefix):$result;
}
本文介绍了一种PHP中用于截取包含中文字符的字符串的方法,该方法能够有效避免乱码问题,并支持不同编码格式的字符串输入。通过使用正则表达式匹配字符集,实现了灵活且高效的字符串截取。
396

被折叠的 条评论
为什么被折叠?



