有时显示的时候只需要部分文字,需要截取

1. 可以用CSS来做

<div style="width:400px;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;">中文显示部分</div>多余400px的部分会以...省略号的形式显示

2. 程序

补充:getSubContent($content, $needL, $multi=3) 最后一个参数写2还是3是由php保存的文件编码来决定的,uft8一个汉字占用3个字节, ANSI, GB2312 只有2个字节


<?php
//get short title
//parameter $content: the Chinese sentence you want to cut
//          $needL, word quantity
//          $multi, one word takes how many chars, Chinese is 2 or 3, English is 1

function getSubContent($content, $needL, $multi=3)
{
    
$pat = '/[\s|\d|,|.|?|\\|\/|:|;|\'|\"|\[|\{|\}|\]|+|=|-|_|)|(|*|&|^|%|$|#|@|!|~|`]/';
    
$arr = preg_split($pat$content);
    
$enLength = $needL;
               
    
$transmitL = $needL * $multi;
    if ( 
$multi != 1 && $transmitL >= strlen($content))
    {
        return 
$content;
    }
    if ( 
$multi == 1  && $needL >= count($arr) )
    {
        return 
$content;
    }
            
    
$totalL = 0;
    
$textL = 0;
    
$markNum = 0;
    
$i = 0 ;
    foreach (
$arr as $key => $a)
    {
        
$i++;
        
$textL = strlen($a);
                
        if (
$multi != 1) {
            if ((
$totalL + $textL  ) >= $transmitL)
            {
                
$stillNeed = $transmitL - $totalL ;
                        
                
$calculateL = $totalL + $stillNeed + $markNum ;
                break;
            }
        } else {
            if (
$i == $enLength )
            {
                
$calculateL = $totalL + $textL + $markNum ;
                break;
             }
        }
        
$markNum += 1;
        
$totalL += $textL ;
    }
    return substr( 
$content, 0, $calculateL);
}
$str = '繁,体!中,,文繁体中文繁体中文繁体中文繁体中文繁体中文繁体中文繁体中文';
echo getSubContent(
$str, 5, 2); // 繁,体!中,,
$str = 'How can love so beautiful never stop the way!';
echo getSubContent(
$str, 5, 1); //How can love so beautiful
?>