汉字截取的方法

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

$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 个字节。

Tags: php, 汉字

相关日志

If you enjoyed this post, please consider to leave a comment or subscribe to the feed and get future articles delivered to your feed reader.

Comments

这个我没弄明白是怎么回事?

一般是用在首页的文章、新闻、评论等的调用,需要显示部分内容的时候,多余的内容用......代替

发表评论

(必填)

(必填)


*
To prove you're a person (not a spam script), type the security word shown in the picture. Click on the picture to hear an audio file of the word.
Click to hear an audio file of the anti-spam word

Comment moderation is enabled. Your comment may take some time to appear.