头像

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

2017-09-27 10:48:10 来源:PHP代码   浏览()   评论 ( 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
声明:转载请注明来源(PHP代码)并保留原文链接:http://www.phpdaima.com//it-13.html
广告不存在
评论0

后面还有条评论,点击查看>>

温馨提示:为规范评论内容,垃圾评论一律封号...