It is estimated that many children who play smarty template have encountered the problem of cutting garbled characters. Especially the UTF8 encoded.
The following code is saved as modifier.truncate2.php to the plugin directory under Smarty Libs
And then cut it with $v->content|truncate2:100.
It's done.
If not good may be the cache caused, please speed to delete the cache file under Templates_c (small series engaged in the time of the cache problems encountered.) )
Copy CodeThe code is as follows:
/**
* Smarty Plugin
* @package Smarty
* @subpackage Plugins
*/
/**
* Smarty truncate modifier plugin
*
* Type:modifier
* Name:truncate
* Purpose:truncate A string to a certain length if necessary,
* Optionally splitting in the middle of a word, and
* Appending the $ETC string or inserting $etc into the middle.
* @link http://smarty.php.net/manual/en/language.modifier.truncate.php
* Truncate (Smarty online manual)
* @author Monte Ohrt
* @param string
* @param integer
* @param string
* @param boolean
* @param boolean
* @return String
*/
function Smarty_modifier_truncate2 ($string, $length = $, $etc = ' ... ', $count _words = True) {
Return $returnstr =substr_utf8 ($string, 0, $length). $etc;
}
function Substr_utf8 ($str, $start =0, $length =-1, $return _ary=false) {
$len = strlen ($STR); if ($length = =-1) $length = $len;
$r = Array ();
$n = 0;
$m = 0;
for ($i = 0; $i < $len; $i + +) {
$x = substr ($str, $i, 1);
$a = Base_convert (ord ($x), 10, 2);
$a = substr (' 00000000 '. $a,-8);
if ($n < $start) {
if (substr ($a, 0, 1) = = 0) {
}elseif (substr ($a, 0, 3) = = 110) {
$i + = 1;
}elseif (substr ($a, 0, 4) = = 1110) {
$i + = 2;
}
$n + +;
}else {
if (substr ($a, 0, 1) = = 0) {
$r [] = substr ($str, $i, 1);
}elseif (substr ($a, 0, 3) = = 110) {
$r [] = substr ($str, $i, 2);
$i + = 1;
}elseif (substr ($a, 0, 4) = = 1110) {
$r [] = substr ($str, $i, 3);
$i + = 2;
}else {
$r [] = ";
}
if (+ + $m >= $length) {
Break
}
}
}
Return $return _ary? $r: Implode ("", $r);
}
/* Vim:set expandtab: */
?>
Samrty's plug-in system is more intelligent and easy to modify.