怎么控制php中新闻标题的字数

如题所述

控制长度当然是字符串截取了,不过这个不是在大型网站中最好的处理方法,因为截取后的不完整标题无法表达文章的大意,一般都是有一个ShortTitle由编辑填写,字数根据页面需要由编辑来控制。 字符串截取的方法中当然是支持中文的最好,提供两个给你参考。 /**
* @name substr_gbk
* @Desc 字符串截取函数,适用于GBK编码的字符串
* @author 十月GG(TaoShuChen)
* @param $str String 目标字符串
* @param $length int 所需截取的长度
* @param $other String 是否添加后缀
* @return $rstr String 截取后的字符串
*/
function substr_gbk($str,$length=10,$other='...') {
for($i=0,$j=0;$i<$length;$i++){
if(ord(substr($str,$i,1))>0xa0){
$j++;
}
}
if($j%2!=0) $length++;
$rstr=substr($str,0,$length);
if (strlen($str)>$length && !empty($other)) {
$rstr.= $other;
}
return $rstr;
} /**
* @name substr_utf8
* @Desc 字符串截取函数,适用于UTF8编码的字符串
* @author 十月GG(TaoShuChen)
* @param $str String 目标字符串
* @param $start int 开始位置
* @param $length int 所需截取的长度
* @param $other String 是否添加后缀
* @return $result String 截取后的字符串
*/function substr_utf8($str, $start=0, $length=10, $other='...') {
$pa="/[\x01-\x7f]|[\xc2-\xdf][\x80-\xbf]|\xe0[\xa0-\xbf][\x80-\xbf]|[\xe1-\xef][\x80-\xbf][\x80-\xbf]|";
$pa.="\xf0[\x90-\xbf][\x80-\xbf][\x80-\xbf]|[\xf1-\xf7][\x80-\xbf][\x80-\xbf][\x80-\xbf]/";
preg_match_all($pa, $str, $t_string);
if(count($t_string[0]) - $start > $length && !empty($other)) {
return $result = implode('', array_slice($t_string[0], $start, $length)) . $other;
} else {
return $result = implode('', array_slice($t_string[0], $start, $length));
}
}
温馨提示:答案为网友推荐,仅供参考
第1个回答  2013-07-22
你可以用字符截取啊。。可以用substr函数。。substr (PHP 3, PHP 4, PHP 5)substr -- Return part of a string $str ='新闻标题好长长。。。。。'echo substr($str, 4);本回答被网友采纳
第2个回答  2013-07-22
/**作用:统计字符长度包括中文、英文、数字
* 参数:需要进行统计的字符串、编码格式目前系统统一使用UTF-8
* 时间:2009-07-15
* 修改记录:
$str = "kds";
echo sstrlen($str,'utf-8');
* */
function sstrlen($str,$charset) {
$n = 0; $p = 0; $c = '';
$len = strlen($str);
if($charset == 'utf-8') {
for($i = 0; $i < $len; $i++) {
$c = ord($str{$i});
if($c > 252) {
$p = 5;
} elseif($c > 248) {
$p = 4;
} elseif($c > 240) {
$p = 3;
} elseif($c > 224) {
$p = 2;
} elseif($c > 192) {
$p = 1;
} else {
$p = 0;
}
$i+=$p;$n++;
}
} else {
for($i = 0; $i < $len; $i++) {
$c = ord($str{$i});
if($c > 127) {
$p = 1;
} else {
$p = 0;
}
$i+=$p;$n++;
}
}
return $n;
}
第3个回答  2013-07-22
同上 还有就是css截取 这个办法比较好 因为是前台 跟后台没关系了
相似回答