新手, 在做一个普通的从数据库读取标题的时候, 在输出的地方 width 不够,换行了,我想用 ... 代替, 怎么用php 来实现啊, 网上有很多 PHP 截取字符串的函数来着, 什么substr 啊, 刚开始学, 不太懂, 麻烦大家帮忙 写一个仔细点的。这是 读取数据的部分,我只想让前台显示8个字符,剩下的用 ...代替, 如果写函数 我应该加到哪呢?? 具体些。<div class="news_new">
<ul>
<?php
while($arr=mysql_fetch_array($result)){
?>
<li <?php echo $arr[title]; ?></a></li>
<?php
}
?>
</ul>
</div>
<ul>
<?php
while($arr=mysql_fetch_array($result)){
?>
<li <?php echo $arr[title]; ?></a></li>
<?php
}
?>
</ul>
</div>
就是 php 的 具体点。 谢谢。
谢谢。我用了 $title=mb_strimwidth($title, 0, 16, "...");怎么出现了 "?" 呢?? 是所说的 乱码吗?
假如是中文:<div class="news_new">
<ul>
<?php
while($arr=mysql_fetch_array($result)){
$a=mb_strlen($arr[title],gb2312); //得到你title的长度,一个汉字两个字符
if($a > 8)
{
$arr[tite]=mb_substr($arr[title],gb2312)."…";
}?>
<li <?php echo $arr[title]; ?></a></li>
<?php
}
?>
</ul>
</div>
????
/*
Utf-8、gb2312都支持的汉字截取函数
cut_str(字符串, 截取长度, 开始长度, 编码);
编码默认为 utf-8
开始长度默认为 0
*/function cut_str($string, $sublen, $start = 0, $code = 'UTF-8')
{
if($code == 'UTF-8')
{
$pa ="/[\x01-\x7f]|[\xc2-\xdf][\x80-\xbf]|\xe0[\xa0-\xbf][\x80-\xbf]|[\xe1-\xef][\x80-\xbf][\x80-\xbf]|\xf0[\x90-\xbf][\x80-\xbf][\x80-\xbf]|[\xf1-\xf7][\x80-\xbf][\x80-\xbf][\x80-\xbf]/";
preg_match_all($pa, $string, $t_string); if(count($t_string[0]) - $start > $sublen) return join('', array_slice($t_string[0], $start, $sublen))."...";
return join('', array_slice($t_string[0], $start, $sublen));
}
else
{
$start = $start*2;
$sublen = $sublen*2;
$strlen = strlen($string);
$tmpstr = ''; for($i=0; $i<$strlen; $i++)
{
if($i>=$start && $i<($start+$sublen))
{
if(ord(substr($string, $i, 1))>129)
{
$tmpstr.= substr($string, $i, 2);
}
else
{
$tmpstr.= substr($string, $i, 1);
}
}
if(ord(substr($string, $i, 1))>129) $i++;
}
if(strlen($tmpstr)<$strlen ) $tmpstr.= "...";
return $tmpstr;
}
}$str = "abcd需要截取的字符串"; //标题
echo cut_str($str, 1, 0, 'gb2312');
?>
刚才测试,效果相当好。