频道栏目
首页 > 资讯 > 正则表达式 > 正文

正则应用实例-简单模仿smarty

16-01-07        来源:[db:作者]  
收藏   我要投稿
smarty的功能非常强大,不是下面几行代码可以实现的,但是我们可以取出其中的一部分,通过正则实现,比如简单的assign,display,编译缓存,内容缓存等,我们这里只是一个Demo,基本实现了assign和display,以及编译文件的缓存。其实内容的缓存也非常简单,就是文件的写入操作,包括缓存周期,物理文件路径等。这些都可以通过文件操作实现,但由于篇幅所限,所以这里不再赘述。
平板视图
打印
1 // index.php文件是个入口文件,代码如下
2 require_once('my_smarty.php');
3 $demo=newMyTpl();
4 $demo->assign('title','smarty demo');
5 $demo->assign('content','hello iphper');
6 $demo->display('index.html');
平板视图
打印
 
01 // my_smarty.php代码如下 这是一个类
02 classMyTpl {
03 private$template_dir;
04 private$compile_dir;
05 private$tpl_vars=array();
06   
07 publicfunction__construct($template_dir='./template',$compile_dir='./compile') {
08   
09 // 默认模板目录和编译之后的文件目录都在当前文件下面
10 $this->template_dir = rtrim($template_dir,'/').'/';
11 $this->compile_dir = rtrim($compile_dir,'/').'/';
12 }
13 publicfunctionassign($tpl_var,$value=null) {
14 if($tpl_var!='') {
15 $this->tpl_vars[$tpl_var] =$value;
16 }
17 }
18 publicfunctiondisplay($file_name) {
19 $tpl_file=$this->template_dir.$file_name;
20 if(!file_exists($tpl_file)) {
21 returnfalse;
22 }
23   
24 // 编译文件的命名规则
25 $compile_file_name=$this->compile_dir.'com_'.$file_name.'.php';
26   
27 // 当编译文件不存在或者修改之后重新编译文件
28 if(!file_exists($compile_file_name) ||filemtime($tpl_file) >filemtime($compile_file_name)){
29 $compile_file_content=$this->tpl_replace(file_get_contents($tpl_file));
30 file_put_contents($compile_file_name,$compile_file_content);
31 }
32 include($compile_file_name);
33 }
34   
35 privatefunctiontpl_replace($content) {
36   
37 // 正则的运用 匹配替换
38   
39 $pattern=array('/\{\s*\$([a-zA-Z_]\w*)\s*\}/i');
40   
41 $replace=array('tpl_vars["${1}"];?>');
42   
43 // 注意如何反引用 ${1} 等价 \\1
44   
45 $replaced= preg_replace($pattern,$replace,$content);
46   
47 return$replaced;
48 }
49 }
平板视图
 
打印
1 // 模板文件 位于template目录下
2
3456{$content}
good7平板视图 打印? 1 // 模板编译后的文件 位于compile目录下 23456tpl_vars["content"];?>
good7上述实例涉及到php面向对象的一些知识点,所以不太适合初学者。但是目前个人时间原因就给了这个例子,其他控制用户输入的正则很多,网上比比皆是,所以就略去了。但是并不代表我们会了,所以有时间要多看看别人怎么写,自己多应用应用,孰能生巧。正则强大的功能有待我们继续探讨,以后我将继续给出相关综合实例。
相关TAG标签
上一篇:php cookie登录验证代码
下一篇:PHP精编面试题–PHP面试宝典
相关文章
图文推荐

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

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