教程集 www.jiaochengji.com
教程集 >  脚本编程  >  php  >  正文 smarty截取字符串truncate函数介绍

smarty截取字符串truncate函数介绍

发布时间:2023-05-10   编辑:jiaochengji.com
教程集为您提供smarty截取字符串truncate函数介绍等资源,欢迎您收藏本站,我们将为您提供最新的smarty截取字符串truncate函数介绍资源
以前不知道smarty模板中还可以直接使用truncate函数来截取字符串,还非得利用php来截取好字符串后传给smarty模板,现在才发现,下面我来介绍truncate用法。


具体用法如下:

 代码如下 复制代码

//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字节不能表示一个汉字,那么它就会以乱码的形式显示出来

解决办法

 代码如下 复制代码

<?php
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内容函数即可了,大家可参考。

您可能感兴趣的文章:
smarty截取字符串truncate函数介绍
smarty获得当前url示例代码
php如何截取字符串后四位
php中文字符截取函数(自用)
php中文截取字符串mb_substr的用法
smarty模板引擎中英文多编码字符截取出现乱码问题的解决方法
php截取中文字符串的二个函数(iconv_substr和mb_substr)
js 字符串截取与数组截取方法
smarty入门教程六[使用phplib的DB类]
php中文字符串截取方法

[关闭]
~ ~