如何实现给文章内链自定义关键词(关键词自定义URL版)
官方内链 是直接输出 搜索地址或者是 tag库地址
https://www.xunruicms.com/doc/405.html
但是很多人希望是自定义URL,那就参考下面去写
将下面代码放在 config/custom.php 里
调用方法:{tag_link($content,$neilian)}
这里的 $kws 是一个数组
格式为: ['关键词'=>URL,'关键词'=>URL,'关键词'=>URL]
我们可以通过全局表单实现这个关键词库,
新建一个表单,
内链库/nlk
默认字段有 title
自定义一个字段 url
下面是 show.html 调用 ,首先用 form 循环输出一个关键词数组,然后填到 tag_link 函数里进行匹配
{form form=nlk num=10}
{php
$neilian = [];
$neilian[$t.title] = $t.url;
}
{/form}
{tag_link($content,$neilian)}//
// 将下面代码放在 config/custom.php 里
//
// 调用方法:
// {tag_link($content,$neilian)}
//
function tag_link($content,$posttags,$match_num_from = 1,$match_num_to = 1){
//$match_num_from = 1; 一篇文章中同一个标签少于几次不自动链接
//$match_num_to = 1; 一篇文章中同一个标签最多自动链接几次
if ($posttags) {
$new = [];
foreach($posttags as $k => $v) {
$new[] = ['link'=>$v,'name'=>$k];
}
$posttags = $new;
usort($posttags, "tag_sort");
foreach($posttags as $tag) {
$link = $tag['link'];
$keyword = $tag['name'];
$cleankeyword = stripslashes($keyword);
$url = "<a href=\"$link\" title=\"".str_replace('%s',addcslashes($cleankeyword, '$'),('点击了解更多关于[%s]的文章'))."\"";
$url .= ' target="_blank"';
$url .= ">".addcslashes($cleankeyword, '$')."</a>";
$limit = rand($match_num_from,$match_num_to);
$content = preg_replace( '|(<a[^>]+>)(.*)('.$ex_word.')(.*)(</a[^>]*>)|U'.$case, '$1$2%&&&&&%$4$5', $content);
$content = preg_replace( '|(<img)(.*?)('.$ex_word.')(.*?)(>)|U'.$case, '$1$2%&&&&&%$4$5', $content);
$cleankeyword = preg_quote($cleankeyword,'\'');
$regEx = '\'(?!((<.*?)|(<a.*?)))('. $cleankeyword . ')(?!(([^<>]*?)>)|([^>]*?</a>))\'s' . $case;
$content = preg_replace($regEx,$url,$content,$limit);
$content = str_replace( '%&&&&&%', stripslashes($ex_word), $content);
}
}
return $content;
}
function tag_sort($a, $b){
if ( $a->name == $b->name ) return 0;
return ( strlen($a->name) > strlen($b->name) ) ? -1 : 1;
}
下面是 show.html 调用 ,首先用 form 循环输出一个关键词数组,然后填到 tag_link 函数里进行匹配 {form form=nlk num=10} {php $neilian = []; $neilian[$t.title] = $t.url; } {/form} {de_content_link($neilian,$content,1)}{dr_content_link($neilian,$content,1)}