码迷,mamicode.com
首页 > Web开发 > 详细

Thinkphp 文章关键词自动加链接-内链模块

时间:2016-03-07 13:47:19      阅读:1864      评论:0      收藏:0      [点我收藏+]

标签:

 

Thinkphp 文章关键词自动加链接-内连模块
首先建立关键词表 命名为 xx_sitelink

表结构 id   link keyword

在前台项目下新建 ReplaceAction.class.php文件,建立替换链接模块 

 

<?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 ="/((?<!<))($pattern)(?![^<>]*(?:>|<\/a>))/";
   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 "<a href=‘$link‘>$matches[2]</a>";
}

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);

?>

 

Thinkphp 文章关键词自动加链接-内链模块

标签:

原文地址:http://www.cnblogs.com/afeng2016/p/5250023.html

(2)
(5)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!