查找到文中的关键字,给关键字添加上超级连接,若是有进行关键词替换的需求仍然能够基于这个类进行修改。
替换顺序按照数组的索引来的,能够把规则写入数据里,并添加权重字段,能够动态调整关键词替换或者添加超级连接的优先级。php
<?php /** * 给文章中的匹配到字符添加上a链接 * Created by PhpStorm. * User: smallForest<1032817724@qq.com> * Date: 2019-06-06 * Time: 09:19 */ class addLink { protected $content = ''; protected $replace_rules = []; public function __construct($content, $replace_rules) { $this->content = $content; $this->replace_rules = $replace_rules; } public function do_replace() { //执行替换返回替换后的字符串 if (!empty($this->replace_rules)) { foreach ($this->replace_rules as $rule) { $this->content = preg_replace('/(?!<[^>]*)' . $rule['key_word'] . '(?![^<]*(>|<\/[a|sc]))/s', '<a href="' . $rule['url'] . '" target="' . $rule['target'] . '" >' . $rule['key_word'] . "</a>", $this->content, $rule['replace_times'], $count);//经过判断count字段大于0 能够得知替换结果 } } return $this->content; } } $rule = [ [ 'key_word' => '中国人',//关键词 'url' => 'http://www.baidu.com?id=中国人',//须要加的超链 'target' => '_blank',//打开方式 'replace_times' => 1,//容许替换的次数次数 -1为不限制次数! ], [ 'key_word' => '中国',//关键词 'url' => 'http://www.baidu.com?id=中国',//须要加的超链 'target' => '_blank',//打开方式 'replace_times' => 1,//容许替换的次数次数 -1为不限制次数! ], [ 'key_word' => '人', 'url' => 'http://www.baidu.com?id=人', 'target' => '_blank', 'replace_times' => 1, ], ]; $obj = new addLink('我是中国人', $rule); echo $obj->do_replace();