內容截取函數

/**
 * 內容截取
 *
 * @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

相關文章
相關標籤/搜索