信息发布→ 登录 注册 退出

C#自动给文章关键字加链接实现代码

发布时间:2026-01-11

点击量:

主要做的是,文章中的关键字标签加上链接,网上也有很多解决办法,自己整理以便后续在用。

效果如图:

下面是代码:

复制代码 代码如下:
/// <summary>
        /// 内联
        /// </summary>
        /// <param name="content"></param>
        /// <returns></returns>
        public string ReplaceTextTag(string content)
        {
            A  a = new A();
            string result = "";
            if (!string.IsNullOrEmpty(content))
            {
                //标签
                List<Tag> listAll = a .GetTag(); 获取标签也就是所谓的关键字
                string str1 = content;
                result = keyAddUrl(str1, listAll);
            }
            return result;
        }
        /// <summary>
        /// 加title,加链接
        /// </summary>
        /// <param name="src"></param>
        /// <param name="keys"></param>
        /// <returns></returns>
        private string keyAddUrl(string src, List<TopicTag> keys)
        {
            Regex reg = new Regex(@"(?i)(?:^|(?<!<a\b(?>[^<>]*))>)(?>[^<>]*)(?:<|$)");
            int length = 0;
            string temp = string.Empty;
            return reg.Replace(src, delegate(Match m)
            {
                temp = m.Value;
                length = temp.Length;
                for (int i = keys.Count - 1; i >= 0; i--)
                {
                    temp = Regex.Replace(temp, @"(?is)^((?:(?:(?!" + Regex.Escape(keys[i].Label) + @"|</?a\b).)*<a\b(?:(?!</?a\b).)*</a>)*(?:(?!" + Regex.Escape(keys[i].Label) + @"|</?a\b).)*)(?<tag>" + Regex.Escape(keys[i].Label) + @")",
                        @"$1<a href=""http://cn.greatexportimport.com/topic-" + keys[i].Id + @""" target=""_blank"" title=""${tag}"">${tag}</a>");
                    if (length != temp.Length)
                    {
                        keys.Remove(keys[i]);
                    }
                    length = temp.Length;
                }
                return temp;
            });
        }

在页面调用此方法即可:<p><%=Tag.ReplaceTextTag(Tag.Contents)%></p><br />

标签:# result  # src  # span  # summary  # lt  # string  # GetTag  # keyAddUrl  # title  # return  # listAll  # 关键字链接  # ReplaceTextTag  # IsNullOrEmpty  # Tag  # List  # 网上  # 解决办法  # 如图  # 也有  # 的是  # C#  
在线客服
服务热线

服务热线

4008888355

微信咨询
二维码
返回顶部
×二维码

截屏,微信识别二维码

打开微信

微信号已复制,请打开微信添加咨询详情!