文章关键字加链接


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

效果如图:

下面是代码:

 1  /// 
 2         /// 内联
 3         /// 
 4         /// 
 5         /// 
 6         public string ReplaceTextTag(string content)
 7         {
 8             A  a = new A();
 9             string result = "";
10             if (!string.IsNullOrEmpty(content))
11             {
12                 //标签
13                 List listAll = a .GetTag(); 获取标签也就是所谓的关键字
14                 string str1 = content;
15                 result = keyAddUrl(str1, listAll);
16             }
17             return result;
18         }
19         /// 
20         /// 加title,加链接
21         /// 
22         /// 
23         /// 
24         /// 
25         private string keyAddUrl(string src, List keys)
26         {
27             Regex reg = new Regex(@"(?i)(?:^|(?[^<>]*))>)(?>[^<>]*)(?:<|$)");
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) + @"|)*(?:(?!" + Regex.Escape(keys[i].Label) + @"|" + Regex.Escape(keys[i].Label) + @")",
37                         @"$1" + keys[i].Id + @""" target=""_blank"" title=""${tag}"">${tag}");
38                     if (length != temp.Length)
39                     {
40                         keys.Remove(keys[i]);
41                     }
42                     length = temp.Length;
43                 }
44                 return temp;
45             });
46         }

在页面调用此方法即可:

<%=Tag.ReplaceTextTag(Tag.Contents)%>