/**
* 截取文章内容中指定长度的字符内容
* @param string $text 文章内容
* @param string $length 要截取的字符个数
* return string 返回截取后的字符内容
*/
public function truncateText($text, $length=100)
{
// 去除所有HTML标签和属性
$text = strip_tags($text);
$text = str_replace('\n', '', $text);
$text = str_replace('\t', '', $text);
$text = str_replace('<img', '', $text); // 去除图片标签
$text = str_replace('src=', '', $text); // 去除图片标签
$text = str_replace('<br', '', $text); // 去除换行标签
// 检查是否为中文字符串
if (preg_match('/[\x{4e00}-\x{9fa5}]/u', $text)) {
// 转换为 UTF-8 编码
$text = mb_convert_encoding($text, 'UTF-8');
// 计算中文字符数量
$chineseLength = mb_strlen($text, 'UTF-8');
// 如果字符数量超过指定长度,进行截取
if ($chineseLength > $length) {
$text = mb_substr($text, 0, $length, 'UTF-8');
$text = rtrim($text); // 去除尾部的空格或其他不可见字符
$text .= '...'; // 添加省略号
}
} else {
// 非中文字符串,直接计算字符数量
if (strlen($text) > $length) {
$text = substr($text, 0, $length);
$text = rtrim($text); // 去除尾部的空格或其他不可见字符
$text .= '...'; // 添加省略号
}
}
return $text;
}
智享笔记