<?php
namespace Api\Controller;
class ReplaceLinkController extends CommonController{
private $text;
/**
* 外部调用
* @param $text
* @return string|string[]|null
*/
public function content($text){
$this->text = $text;
$content = $this->replace();
return $content;
}
/**
* 替换函数
* @return string|string[]|null
*/
private function replace(){
$keywords = $this->keywords();
$pattern = implode('|',array_keys($keywords));
$pattern ="/((?<!<))($pattern)(?![^<>]*(?:>|<\/a>))/";
return preg_replace_callback($pattern,array($this,callback),$this->text);
}
/**
* 正则替换回调函数
* @param $matches
* @return string
*/
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>";
}
/**
* 查找关键词
* @return mixed
*/
private function keywords(){
$keywords = M('keyword_link')->where(['keyword'=>['neq','']])->select();
foreach ($keywords as $key => $value) {
if (strpos($this->text,$value['keyword'])){
$m[$value['keyword']] = $value['link'];
}
}
//对数组进行逆向排序,最长关键词优先替换
krsort($m);
return $m;
}
}