查找到文中的關鍵字,給關鍵字添加上超級鏈接。
查找到文中的關鍵字,給關鍵字添加上超級鏈接,如果有進行關鍵詞替換的需求仍然可以基於這個類進行修改。
替換順序按照數組的索引來的,可以把規則寫入數據裏,並添加權重字段,可以動態調整關鍵詞替換或者添加超級鏈接的優先級。
<?php
/**
* 給文章中的匹配到字符添加上a連接
* Created by PhpStorm.
* User: smallForest<[email protected]>
* 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();