汉字截取的方法

转载时请标明文章原始出处和作者信息, 作者: lostsnow.
http://www.lsproc.com/blog/intercept-chinese-char/

原来有人提出了一个方法:

$len = 19;
$text = "here is the text!";
echo strlen($text)< =$len ? $text : (substr($text,0,$len).chr(0)."....");

在 SaBlog 的程序里发现了另一种方法:

function csubstr ($text, $limit) {
    $s = ';
    for($i=0;$i< $limit-3;$i++) {
        $s .= ord($text[$i])>127 ? $text[$i].$text[++$i] : $text[$i];
    }
    return $s;
}

以上仅适用于 gb2312 编码,如果是UTF-8 的话需要把第4行改为

$s .= ord($text[$i])>127 ? $text[$i].$text[++$i].$text[++$i] : $text[$i];

UTF-8 中的汉字是 3 个字节。

-- EOF --

Related Posts

2 thoughts on “汉字截取的方法

发表评论

电子邮件地址不会被公开。 必填项已用 * 标注

*

您可以使用这些 HTML 标签和属性: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>