Home > php教程 > php手册 > 截取指定字数的字符串中文有效

截取指定字数的字符串中文有效

WBOY
Release: 2016-06-13 10:27:42
Original
1473 people have browsed it


function csubStr($str,$start,$len)
{
$strlen=strlen($str);
$clen=0;
for($i=0;$i{
if ($clen>=$start+$len)
break;
if(ord(substr($str,$i,1))>0xa0)
{
if ($clen>=$start)
$tmpstr.=substr($str,$i,2);
$i++;
}
else
{
if ($clen>=$start)
$tmpstr.=substr($str,$i,1);
}
}
return $tmpstr;
}
例子:$str = csubStr("大家好,截取指定字数的字符串,886!",0,10);
通常可以用来显示论坛主题列表,比如配合下面这个函数:
function showShort($str,$len)
{
if($len {
$tempStr = csubStr($str,0,$len);
$tempStr .= "...";
}
else
{
$tempStr =$str;
}
return $tempStr;
}
主题超过指定字数,就截取,然后加上省略号。否则显示全部字数。
eclipse 回复于:2001-11-24 21:39:31 [b][color=red]没多大用处吧?[/color][/b]
bigmouse 回复于:2001-11-29 12:02:54 还是有用处的,如果不判断中文字节就截取的话,当恰好截取到汉字的中间就会出现乱码,毕竟汉字是双字节的,要特殊判断一下。
evil 回复于:2002-11-12 11:42:07 mb_substr就能搞定


wubai 回复于:2002-11-12 11:49:03
还是看看这个吧~~~~~
http://www.chinaunix.net/cgi-bin/bbs/topic.cgi?forum=15&topic=351&show=0
windlike 回复于:2003-05-08 15:13:29 好呀 这个贴子发起的不错呀 我立刻就可以用到了 真是太棒了 感谢诸位
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Recommendations
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template