【smarty截取字符串替换】smarty截取字符串truncate函数介绍

更新时间:2017-11-18    来源:php函数    手机版     字体:

【www.bbyears.com--php函数】


具体用法如下:

 代码如下

//index.php
$smarty = new Smarty;
$smarty->assign("articleTitle", "Two Sisters Reunite after Eighteen Years at Checkout Counter.");
$smarty->display("index.tpl");
//index.tpl
{$articleTitle}
{$articleTitle|truncate}
{$articleTitle|truncate:30}
{$articleTitle|truncate:30:""}
{$articleTitle|truncate:30:"---"}
{$articleTitle|truncate:30:"":true}
{$articleTitle|truncate:30:"...":true}

输出结果:

Two Sisters Reunite after Eighteen Years at Checkout Counter.
Two Sisters Reunite after Eighteen Years at Checkout Counter.
Two Sisters Reunite after…
Two Sisters Reunite after
Two Sisters Reunite after—
Two Sisters Reunite after Eigh
Two Sisters Reunite after E…

如果上面是英文肯定没有问题,但是出现中文好像就是乱码了,因为Smarty的truncate截取的是字符(占一个字节),

但是如果是中文,例如UTF-8(占3个字节),那么在截取的时候这里的参数11是字节数,如果是中文,则它实际上是截

取3个汉字(9个字节),剩下的2字节不能表示一个汉字,那么它就会以乱码的形式显示出来

解决办法

 代码如下

function smarty_modifier_truncate_utf($string, $length = 80, $etc = "...")
{
 $result = "";
 $string = html_entity_decode(trim(strip_tags($string)), ENT_QUOTES, "utf-8");
 for($i = 0, $j = 0; $i < strlen($string); $i++)
 {
  if($j >= $length)
  {
   for($x = 0, $y = 0; $x < strlen($etc); $x++)
   {
    if($number = strpos(str_pad(decbin(ord(substr($string, $i, 1))), 8, "0", STR_PAD_LEFT), "0"))
    {
     $x += $number - 1;
     $y++;
    }
    else
    {
     $y += 0.5;
    }
   }
   $length -= $y;
   break;
  }
  if($number = strpos(str_pad(decbin(ord(substr($string, $i, 1))), 8, "0", STR_PAD_LEFT), "0"))
  {
   $i += $number - 1;
   $j++;
  }
  else
  {
   $j += 0.5;
  }
 }
 for($i = 0; (($i < strlen($string)) && ($length > 0)); $i++)
 {
  if($number = strpos(str_pad(decbin(ord(substr($string, $i, 1))), 8, "0", STR_PAD_LEFT), "0"))
  {
   if($length < 1.0)
   {
    break;
   }
   $result .= substr($string, $i, $number);
   $length -= 1.0;
   $i += $number - 1;
  }
  else
  {
   $result .= substr($string, $i, 1);
   $length -= 0.5;
  }
 }
 $result = htmlentities($result, ENT_QUOTES, "utf-8");
 if($i < strlen($string))
 {
  $result .= $etc;
 }
 return $result;
}
?>

修改smarty内容函数即可了,大家可参考。

本文来源:http://www.bbyears.com/jiaocheng/37143.html

猜你感兴趣