乐趣区

查找到文中的关键字给关键字添加上超级链接

查找到文中的关键字,给关键字添加上超级链接。

查找到文中的关键字,给关键字添加上超级链接,如果有进行关键词替换的需求仍然可以基于这个类进行修改。
替换顺序按照数组的索引来的,可以把规则写入数据里,并添加权重字段,可以动态调整关键词替换或者添加超级链接的优先级。

<?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();
退出移动版