该楼层疑似违规已被系统折叠 隐藏此楼查看此楼
Thinkphp 文章关键词自动加链接-内连模块
首先建立关键词表 命名为 xx_sitelink
表结构 id link keyword
在前台项目下新建 ReplaceAction.class.php文件,建立替换链接模块
class ReplaceAction extends Action{
private $text;
public function __toString() {return $this->replace();}//返回替换结果
public function content($text){$this->text=$text;}//获取内容给$text
private function replace(){ //替换函数
$keywords=$this->keywords();
$pattern =implode('|',array_keys($keywords));
$pattern ="/((?]*(?:>|))/";
return preg_replace_callback($pattern,array($this,callback),$this->text);
}
private function callback($matches) { //正则替换回调函数
global $log; //替换记录,替换过则不在进行相同替换
if($log[$matches[2]])
return $matches[0];
$log[$matches[2]]=true;
$keywords = $this->keywords();
$link = $keywords[$matches[2]];
return "$matches[2]";
}
private function keywords(){ //查找关键词
$Keywords = M("Sitelink");
$Keywords = $Keywords->where("link<>''")->select();
foreach ($Keywords as $key => $value) {
if (strpos($this->text,$value[keyword])){ //内容中包含关键词存入数组
$m[$value[keyword]]=$value[link];
}
}
krsort($m);//对数组进行逆向排序,最长关键词优先替换
return $m;
}
}
同项目下调用 $Form = M('text');
$data = $Form->find($id);
if($data) {
$Replace = A("Replace");
$Replace ->content($data[content]); //$data[content]为你的正文字段
$data[content]=$Replace;
}
$this -> assign('data',$data);