文章关键字加链接

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

效果如图:

下面是代码:

 1  /// <summary>
 2         /// 内联
 3         /// </summary>
 4         /// <param name="content"></param>
 5         /// <returns></returns>
 6         public string ReplaceTextTag(string content)
 7         {
 8             A  a = new A();
 9             string result = "";
10             if (!string.IsNullOrEmpty(content))
11             {
12                 //标签
13                 List<Tag> listAll = a .GetTag(); 获取标签也就是所谓的关键字
14                 string str1 = content;
15                 result = keyAddUrl(str1, listAll);
16             }
17             return result;
18         }
19         /// <summary>
20         /// 加title,加链接
21         /// </summary>
22         /// <param name="src"></param>
23         /// <param name="keys"></param>
24         /// <returns></returns>
25         private string keyAddUrl(string src, List<TopicTag> keys)
26         {
27             Regex reg = new Regex(@"(?i)(?:^|(?<!<a(?>[^<>]*))>)(?>[^<>]*)(?:<|$)");
28             int length = 0;
29             string temp = string.Empty;
30             return reg.Replace(src, delegate(Match m)
31             {
32                 temp = m.Value;
33                 length = temp.Length;
34                 for (int i = keys.Count - 1; i >= 0; i--)
35                 {
36                     temp = Regex.Replace(temp, @"(?is)^((?:(?:(?!" + Regex.Escape(keys[i].Label) + @"|</?a).)*<a(?:(?!</?a).)*</a>)*(?:(?!" + Regex.Escape(keys[i].Label) + @"|</?a).)*)(?<tag>" + Regex.Escape(keys[i].Label) + @")",
37                         @"$1<a href=""http://cn.greatexportimport.com/topic-" + keys[i].Id + @""" target=""_blank"" title=""${tag}"">${tag}</a>");
38                     if (length != temp.Length)
39                     {
40                         keys.Remove(keys[i]);
41                     }
42                     length = temp.Length;
43                 }
44                 return temp;
45             });
46         }
View Code

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

原文地址:https://www.cnblogs.com/huicao/p/3478118.html