當前位置:學者齋 >

計算機 >php語言 >

php摘要生成函式詳解

php摘要生成函式詳解

以前也寫過一個PHP文章摘要生成方法(函式), 不過,不怎麼好用,也出現亂碼,現在再發佈一個,這個函式是在某開源系統上拆下來了,希望對大家用用。

php摘要生成函式詳解

在使用的時候,得先把要生成摘要的.內容strip_tags()一下,當然,你也可以把strip_tags()直接新增到函式中,我沒有搞,自己新增吧。下面是函式:

  複製程式碼 程式碼如下:

function cutstr($string, $length,$charset,$dot) {//字元,擷取長度,字符集,結尾符

if(strlen($string) <= $length) {

return $string;

}

$pre = chr(1);

$end = chr(1);

//保護特殊字串

$string = str_replace(array('&', '"', '<', '>'), array($pre.'&'.$end, $pre.'"'.$end, $pre.'<'.$end, $pre.'>'.$end), $string);

$strcut = '';

if(strtolower($charset) == 'utf-8') {

$n = $tn = $noc = 0;

while($n < strlen($string)) {

$t = ord($string[$n]);

if($t == 9 || $t == 10 || (32 <= $t && $t <= 126)) {

$tn = 1; $n++; $noc++;

} elseif(194 <= $t && $t <= 223) {

$tn = 2; $n += 2; $noc += 2;

} elseif(224 <= $t && $t <= 239) {

$tn = 3; $n += 3; $noc += 2;

} elseif(240 <= $t && $t <= 247) {

$tn = 4; $n += 4; $noc += 2;

} elseif(248 <= $t && $t <= 251) {

$tn = 5; $n += 5; $noc += 2;

} elseif($t == 252 || $t == 253) {

$tn = 6; $n += 6; $noc += 2;

} else {

$n++;

}

if($noc >= $length) {

break;

}

}

if($noc > $length) {

$n -= $tn;

}

$strcut = substr($string, 0, $n);

} else {

for($i = 0; $i < $length; $i++) {

$strcut .= ord($string[$i]) > 127 ? $string[$i].$string[++$i] : $string[$i];

}

}

  //還原特殊字串

$strcut = str_replace(array($pre.'&'.$end, $pre.'"'.$end, $pre.'<'.$end, $pre.'>'.$end), array('&', '"', '<', '>'), $strcut);

//修復出現特殊字串截段的問題

$pos = strrpos($s, chr(1));

if($pos !== false) {

$strcut = substr($s,0,$pos);

}

return $strcut.$dot;

}

標籤: PHP 摘要 函式
  • 文章版權屬於文章作者所有,轉載請註明 https://xuezhezhai.com/zh-tw/jsj/php/31lpd0.html