/**
* 内容截取
*
* @param $str
* @param int $length
* @param string $ext
* @param string $tag 标签
* @return string
*/
function getShort($str, $length = 20, $ext = '', $tag = "")
{
$str = htmlspecialchars($str);
$str = strip_tags($str);
$str = htmlspecialchars_decode($str);
$str = str_replace('—','—',$str); // 过滤中文的破折号
if ($tag) {
if (is_string($tag)) {
$pretag = "<" . $tag . ">";
$afttag = "</" . $tag . ">";
}
if (is_array($tag)) {
$pretag = "<" . $tag['pre'] . ">";
$afttag = "</" . $tag['aft'] . ">";
}
$str = str_replace($pretag, '$', $str);
$str = str_replace($afttag, '#', $str);
$lastTagLen = strrpos($str, '#') - strrpos($str, '$');
}html
$strlenth = 0;
$output = '';
preg_match_all(
"/[\x01-\x7f]|[\xc2-\xdf][\x80-\xbf]|[\xe0-\xef][\x80-\xbf]{2}|[\xf0-\xff][\x80-\xbf]{3}/",
$str,
$match
);
foreach ($match [0] as $v) {
preg_match("/[\xe0-\xef][\x80-\xbf]{2}/", $v, $matchs);
if (!empty ($matchs [0])) {
$strlenth += 1;
} elseif (is_numeric($v)) {
// $strlenth += 0.545; // 字符像素宽度比例 汉字为1
$strlenth += 0.5; // 字符字节长度比例 汉字为1
} else {
// $strlenth += 0.475; // 字符像素宽度比例 汉字为1
$strlenth += 0.5; // 字符字节长度比例 汉字为1
}.net
if ($strlenth > $length) {
$output .= $ext;
break;
}code
$output .= $v;
}htm
if ($tag) {
$count1 = substr_count($output, "$");
$count2 = substr_count($output, "#");
//存在没有结束的标签
if ($count2 < $count1) {
$last = strrpos($output, '$');
$pre_length = $last + $lastTagLen;
//截取的长度
if ($lastTagLen <= $strlenth - $last) {
$pre_output = substr($output, 0, $pre_length);
$aft_output = substr($output, $pre_length);
$output = $pre_output . "#" . $aft_output;
} else {
$output = $output . "#";
}
}ip
$output = str_replace("$", $pretag, $output);
$output = str_replace('#', $afttag, $output);
}ci
return $output;
}get
{$user_name|getShort=7,'...'}string