频道栏目
首页 > 资讯 > Smarty > 正文

smarty中文截取插件开发示例

16-01-08        来源:[db:作者]  
收藏   我要投稿

smarty无疑是php开发里面目前最流行最出名的模板引擎了,通过使用该模板引擎,给我们的开发工作中带来了极大的方便。下面分享一下 smarty 插件技术(以创建一个 php smarty中文字符串截取为例),充分利用 smarty 的各种特性,使 php smarty 成为我们手中更为锋利的利器,让我们的工作更加快速高效。

(1)首先我们需要了解一下 smarty 及其插件的一些知识

1. 什么是smarty?

smarty是一个使用PHP写出来的模板PHP模板引擎, 是php.net推荐的一个模板系统.

2. 什么是smarty的插件?

smarty的插件是指smarty中的plugins, 是一些嵌入模板内的一些功能性控制语句, smarty中的Variable Modifiers(变量调节)实际就是一些内置的插件。

3. 插件是怎么工作的?

在smarty模板中使用了插件调用语句时动态的载入, 你可以将你写好的插件放入smarty目录中的lib目录下的plugins目录里面, 这样在模板中使用这些插件时它将会被自动载入。

4. 插件有几种类型?

smarty 插件的类型有:function, modifier, block, compiler,prefilter, postfilter, outputfilter, resource, insert,本篇文章我们只分享一下如何开发 function 类型的插件,其它类型的开发方法大同小异,大家可以模仿试试。

5. 如何命名插件?

文件名形式:

type.name.php

type指的是类型,上边提到的几种就是它的选择范围;

name: 自定义的插件名称,本文中使用showNews来命名;

函数名称:

smarty_type_name() smarty:固定位置的固定名称; type与文件名的type一致, name与文件名中的name一致

(2)基础知识明白了,下面就开始开发了。将以下代码拷贝到文件中,命名为 modifier.truncate_cn.php 文件,然后将该文件拷贝到 smarty/lib/plugins/ 目录下面(注意这个目录形式不是固定的,个人根据自己的情况来,但必定是放在plugins目录里面)。

/*
*作者:http://www.php1.cn*/
function smarty_modifier_truncate_cn($string,$length=0,$ellipsis='…',$start=0){
    $string=strip_tags($string);
    $string=preg_replace('/\n/is','',$string);
    //$string=preg_replace('/ | /is','',$string);//清除字符串中的空格
    $string=preg_replace('/ /is','',$string);
    preg_match_all("/[\x01-\x7f]|[\xc2-\xdf][\x80-\xbf]|\xe0[\xa0-\xbf][\x80-\xbf]|[\xe1-\xef][\x80-\xbf][\x80-\xbf]|\xf0[\x90-\xbf][\x80-\xbf][\x80-\xbf]|[\xf1-\xf7][\x80-\xbf][\x80-\xbf][\x80-\xbf]/",$string,$string);
    if(is_array($string)&&!empty($string[0])){
        $string=implode('',$string[0]);
        if(strlen($string)<$start+1){
            return '';
        }
        preg_match_all("/./su",$string,$ar);
        $string2='';
        $tstr='';
        //www.phpernote.com
        for($i=0;isset($ar[0][$i]);$i++){
            if(strlen($tstr)<$start){
                $tstr.=$ar[0][$i];
            }else{
                if(strlen($string2)<$length+strlen($ar[0][$i])){
                    $string2.=$ar[0][$i];
                }else{
                    break;
                }
            }
        }
        return $string==$string2?$string2:$string2.$ellipsis;
    }else{
        $string='';
    }
    return $string;
}
相关TAG标签
上一篇:smarty模板中判断数组为空的方法
下一篇:程序中通过define定义的常量如何在smarty模板中使用
相关文章
图文推荐

关于我们 | 联系我们 | 广告服务 | 投资合作 | 版权申明 | 在线帮助 | 网站地图 | 作品发布 | Vip技术培训 | 举报中心

版权所有: 红黑联盟--致力于做实用的IT技术学习网站