php的输出问题

来源:百度知道 编辑:UC知道 时间:2024/06/15 04:41:04
for ($i=0; $i<$rownum; $i++)
{
$title=$rowdata['title'];
if (strlen($title)>40)
{
$distitle=substr($title,0,39)."…";
}
else
{
$distitle=$title;
}
echo "·<a href=page.php?id=".$rowdata['id']." target=_blank>".$distitle;
echo "</a><br>";
$rowdata=mysql_fetch_array($result);
}
}
我使用substr()限制输出的字数40,可是截取的字符只有20个并出现乱码,如下:
·本视频教程详细介绍了蒙皮和蒙皮变形的结骸?/a>

你的$title读出来是中文的话截取40那么最终显示的只有20个文字,因为一个中文算两个字符,只有数字跟英文字母才是一个整字符
出现乱码的可能性有两种:
1 你用所截取的这个字符串里既有中文也有英文字母跟数字,那么当你截取40个字符的时候前39个字符都截取完了,当你在截取到第四十个字符时遇到的是一个中文那么就只能截取到半个字符,而一个汉字是占两个字符的,这个时候就会在你所截取出来的字符串的未尾产生乱码.
2 编辑器的编码问题.就是整个页面都会出现乱码.

下面这个函数将超过$len长度的字符串转换成以“...”结尾,并且可以避免在截取中文字符串时未尾出现乱码。
用法:$new = getsubstring($old,20);

function getsubstring($str,$len)
{
for($i = 0;$i <$end;$i++)
{
if ($i >=0 AND $i <$end)
{
if(ord(substr($str,$i,1)) > 0xa1)
$result_str.=substr($str,$i,2);
else
$result_str.=substr($str,$i,1);
}
if(ord(substr($str,$i,1)) > 0xa1)
$i++;
}
if(strlen($str)<=$end)
return $result_str;
else
return $result_str."...";
}

汉字是双字节字符,substr() 是用来截取单字节字符的。

#######################################
#功能:带中文的SUBSTR函数
#入口:string
#出口:string
################