In a new project, it is necessary to display the first few lines of pure text part of the article content on the article list page, because the background is an article added through a rich text editor, and the data directly returned is formatted data, resulting in the style of the list page Confusion, so you need to remove the format to return the plain text data.
/**
* 去除Html所有标签、空格以及空白,并截取字符串(包括中文)
* @param string $string 字符串
* @param number $sublength 字符串长度
* @param string $encoding 编码方式
* @param string $ellipsis 省略号
*/
function cutstr_html($string,$sublength,$encoding = 'utf-8',$ellipsis = '…'){
$string = strip_tags($string);
$string = trim($string);
$string = mb_ereg_replace("\t","",$string);
$string = mb_ereg_replace("\r\n","",$string);
$string = mb_ereg_replace("\r","",$string);
$string = mb_ereg_replace("\n","",$string);
$string = mb_ereg_replace(" ","",$string);
if(mb_strlen(trim($string),'utf-8') < $sublength){
return trim($string).$ellipsis;
}else{
return mb_strcut(trim($string),0,$sublength,$encoding).$ellipsis;
}
}
//测试字符串
$str='<p style="microsoft yahei, arial; vertical-align: baseline; list-style-type: none; text-indent: 28px; line-height: 25px; text-align:center;margin-top: 12px; margin-bottom: 12px; padding: 0px; border: 0px; font-size: 14px;color:red;"> fherfhewkolfjlkdsjfld</p>';
//调用方法测试
echo cutstr_html($string=$str,$sublength=5,$encoding='utf-8',$ellipsis='...');
The output is a plain text string of length 5, which can be displayed in the article list.