php技术–易企CMS/smarty截取文章并解析html标签

内容纲要

我们在用smarty或者有朋友用易企CMS做模板时,可能会用到截取字符串的函数,有时候我们的一篇文章中可能会包含大量的html标签,如果大家用smarty自带的truncate过滤器,会发现其中html标签则不会被解析,当我们的文章中有图片等标签时这就显得很麻烦了.

今天我以易企CMS为例和大家分享一个解决的办法,因为易企CMS也是用的smarty模板引擎.这也可以说是一个小小的易企二次开发了哦!不废话,直接看操作:

1.在易企CMS文件夹include\Smarty\libs\plugins下添加一个文件,文件名是modifier.html_substr.php,文件中的内容如下:

/*
* Smarty plugin
*
————————————————————-
* File: modifier.html_substr.php
* Type: modifier
* Name: html_substr
* Version: 1.0
* Date: June 19th, 2003
* Purpose: Cut a string preserving any tag nesting and matching.
* Install: Drop into the plugin directory.
* Author: Original Javascript Code: Benjamin Lupu <lupufr@aol.com>
* Translation to PHP & Smarty: Edward Dale <scompt@scompt.com>
* Modification to add a string: Sebastian Kuhlmann <sebastiankuhlmann@web.de>
*
————————————————————-
*/
function smarty_modifier_html_substr($string, $length, $addstring=””)
{
//$addstring = ” ” . $addstring;if (strlen($string) > $length) {
if( !empty( $string ) && $length>0 ) {
$isText = true;
$ret = “”;
$i = 0;$currentChar = “”;
$lastSpacePosition = -1;
$lastChar = “”;$tagsArray = array();
$currentTag = “”;
$tagLevel = 0;$noTagLength = strlen( strip_tags( $string ) );// Parser loop
for( $j=0; $j<strlen( $string ); $j++ ) {

$currentChar = substr( $string, $j, 1 );
$ret .= $currentChar;

// Lesser than event
if( $currentChar == “<“) $isText = false; // Character handler if( $isText ) { // Memorize last space position if( $currentChar == ” ” ) { $lastSpacePosition = $j; } else { $lastChar = $currentChar; } $i++; } else { $currentTag .= $currentChar; } // Greater than event if( $currentChar == “>” ) {
$isText = true;

// Opening tag handler
if( ( strpos( $currentTag, “<” ) !== FALSE ) && ( strpos( $currentTag, “/>” ) === FALSE ) && ( strpos( $currentTag, ”

// Tag has attribute(s)
if( strpos( $currentTag, ” ” ) !== FALSE ) {
$currentTag = substr( $currentTag, 1, strpos( $currentTag, ” ” ) – 1 );
} else {
// Tag doesn’t have attribute(s)
$currentTag = substr( $currentTag, 1, -1 );
}

array_push( $tagsArray, $currentTag );

} else if( strpos( $currentTag, “= $length) {
break;
}
}

// Cut HTML string at last space position
if( $length < $noTagLength ) {
if( $lastSpacePosition != -1 ) {
$ret = substr( $string, 0, $lastSpacePosition );
} else {
$ret = mb_substr( $string, 0,$length,’UTF-8′ );
$ret.=$addstring;
}
}

// Close broken XHTML elements
while( sizeof( $tagsArray ) != 0 ) {
$aTag = array_pop( $tagsArray );
$ret .= “\n”;
}

} else {
$ret = “”;
}

// only add string if text was cut
if ( strlen($string) > $length ) {
return( $ret );
}
else {
return ( $res );
}
}
else {
return ( $string );
}
}

/* vim: set expandtab: */

?>

2.在模板中使用该过滤器实现想要的效果

{$companysummary|html_substr:360:’….’}

参数说明:

html_substr:过滤器名称,一定要和你的文件名中相对应

360:要保留的字符长度

….:超出的以什么形式显示

 

发表评论

邮箱地址不会被公开。 必填项已用*标注

1 × 9 =