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

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

查找到文中的关键字,给关键字添加上超级链接,如果有进行关键词替换的需求仍然可以基于这个类进行修改。

替换顺序按照数组的索引来的,可以把规则写入数据里,并添加权重字段,可以动态调整关键词替换或者添加超级链接的优先级。

/**

* 给文章中的匹配到字符添加上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'] . '(?![^|

'' . $rule['key_word'] . "",

$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();

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值