PHP文章关键词加链接

<?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;
    }
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

凌晨四点的_LA

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值