Home > Backend Development > PHP Tutorial > php自定义函数截取汉字长度_PHP

php自定义函数截取汉字长度_PHP

WBOY
Release: 2016-06-01 11:53:30
Original
823 people have browsed it
复制代码 代码如下:
function msubstr($str,$start,$len) {
$strlen=$start+$len;
for($i=0;$iif(ord(substr($str,$i,1))>0xa0) {
$tmpstr.=substr($str,$i,2);
$i++;
} else
$tmpstr.=substr($str,$i,1);
}
return $tmpstr;

}

复制代码 代码如下:
$str="这个字符好长呀,^_^";
$Short_Str=showShort($str,4);//截取前面4个汉字,结果为:这个字符...
Echo "$Short_Str";
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;
}
Function showShort($str,$len)
{
$tempstr = csubstr($str,0,$len);
if ($str$tempstr)
$tempstr .= "..."; //要以什么结尾,修改这里就可以.

return $tempstr;
}

再来看看唠叨的方法 怎么样,简洁吧?
复制代码 代码如下:
$len = 19;
$text = "怎么将新闻的很长的标题只显示前面一些字,后面用.....来代替?";
echo strlen($text)
Related labels:
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 Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template