帝国cms专用,长文章分段,不破坏格式。jiuhecai写的智能截取函数: <?php
//智能截取
function AI_mb_substr($str,$length,$encode='utf8',$flags='. ! ? 。 ! ?'){
mb_internal_encoding($encode);
$mylen=mb_strlen($str);
if($mylen<=$length)return $str;
$flagsr=explode(' ',$flags);
for($i=$length;$i<$mylen;$i++){
if(in_array(mb_substr($str,$i,1),$flagsr))break;
}
for($j=$length-1;$j>-1;$j--){
if(in_array(mb_substr($str,$j,1),$flagsr))break;
}
if($j==-1 && $i==$mylen){
}elseif($j==-1){
$length=$i+1;
}elseif($i==$mylen){
$length=$j+1;
}else{
if($i+$j>2*$length){
$length=$j+1;
}else{
$length=$i+1;
}
}
return mb_substr($str,0,$length);
}
//智能分页
function subHtml($html,$length=10,$fenyefu='[!--jiuhecai的分页符--]') {
$result = '';
$tagStack = array();
$len = 0;
//$dlength=$length;
$reallen=mb_strlen(strip_tags($html),'utf8');
if($reallen<$length*1.2)return $html;
$jhcflag=0;
$contents = preg_split("~(<[^>]+?>)~si", $html, -1, PREG_SPLIT_NO_EMPTY | PREG_SPLIT_DELIM_CAPTURE);
foreach($contents as $tag) {
if (trim($tag) == "") continue;
if (preg_match("~<([a-z0-9]+).*?/>~si", $tag)) {
$result .= $tag;
} else if (preg_match("~</([a-z0-9]+).*?>~si", $tag, $match)) {
if (end($tagStack) == $match[1]) {
array_pop($tagStack);
$result .= $tag;
}
} else if (preg_match("~<([a-z0-9]+).*?>~si", $tag, $match)) {
array_push($tagStack, $match[1]);
$result .= $tag;
} else if (preg_match("~<!--.*?-->~si", $tag)) {
$result .= $tag;
} else {
if ($len + mb_strlen($tag,'utf8') < $length) {
$result .= $tag;
$len += mb_strlen($tag,'utf8');
} else {
if(end($tagStack)=='a'){
$result .= $tag;
$len += mb_strlen($tag,'utf8');
}else{
if($jhcflag)break;
$str = AI_mb_substr($tag,$length - $len + 1,'utf8');
$len += mb_strlen($str,'utf8');
$result .= $str;
if($len>$length){
if($tag==$str){
$jhcflag=1;
}else{
break;
}
}
}
}
}
}
$houbu=$qianbu='';
if($tagStack){
$houbu='<'.join($tagStack,'><').'>';
foreach($tagStack as $tag)$qianbu = '</' . $tag . '>'.$qianbu;
}
$html=substr($html,strlen($result));
$result=$result.$qianbu;
if($html){
$html=$houbu.$html;
$result.=$fenyefu.subHtml($html,$length,$fenyefu);
}
return $result;
}
$str = "<div><table>x<tr>1s<td>一二三四<a href=iii title='wo caonima'>5六7八</a>九十一二三四五六七八九10从前有座山,山里只有座庙,苗栗有.个老和尚真是的!</td></tr></table></div>";
echo subHtml($str,6);
|