---
title: "Smarty的输出过滤功能outputfilter"
author: "kisa77"
date: "2010-12-14T13:59:36Z"
tags: ["HTML", "PHP"]
categories: ["编程语言"]
slug: "smarty-outputfilter"
draft: false
lastmod: "2010-12-14T14:08:39Z"
id: 841758
url: "https://kisa77.iteye.com/blog/841758"
---

最近项目中遇到一个问题:  
    页面显示前需要对可能出现的违禁词过滤,之前的做法是使用fetch函数得到编译后的html做正则替换,因为页面不同位置需要设置不同的缓存时间，共执行了三次,导致页面耗时多了0.2s.其实在第一次坐下过滤就足够了,之后访问的都是过滤后的安全内容.  
    翻看smarty源码可知fetch函数执行是页面已经进行了缓存.所以必须在smarty编译前过滤.

    方法1:采用smarty插件的形式,在页面display或fetch之前使用load\_filter函数。

    例：

 

```
 $smarty->load_filter('output','censor'); //censor为插件名字
```

    插件代码：

 

```
function smarty_outputfilter_censor($source, &$smarty)
{
	include(ROOT .'/config/Censor.php');	
	$source = empty($sysCensor['filter']) ? $string : preg_replace($sysCensor['filter']['find'], $sysCensor['filter']['replace'], $source);
    return $source;
}
```

 

这种方法不好的地方就是一旦使用该函数，之后执行的代码都会受影响。如果只想对部分页面进行过滤操作，可以使用下面这种

 

方法2：

使用smarty的register\_outputfilter函数来调用自定义的过滤函数

 

```
$smarty->register_outputfilter(array($this->sysFun,'replaceCensor'));	
```

 register\_outputfilter的参数为array($object,$method)，可以任意调用A类下面的B方法进行过滤。再使用unregister\_outputfilter函数即可对范围内的页面进行过滤

 

```
$smarty->unregister_outputfilter(array($this->sysFun,'replaceCensor'));	
```

 

mark一下，做积累