本节内容:
C#自动给文章关键字加链接的代码。
需求描述:
为文章中的关键字标签加上链接,看看C#中是如何实现的。
效果图,如下所示:
1,自动为文章关键字添加链接的C#代码
复制代码 代码示例:
/// <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)
{ www.jb200.com
Regex reg = new Regex(@"(?i)(?:^|(?<!<ab(?>[^<>]*))>)(?>[^<>]*)(?:<|$)");
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) + @"|</?ab).)*<ab(?:(?!</?ab).)*</a>)*(?:(?!" + Regex.Escape(keys[i].Label) + @"|</?ab).)*)(?<tag>" + Regex.Escape(keys[i].Label) + @")",
@"$1<a href=""http://www.jb200.com/topic-" + keys[i].Id + @""" target=""_blank"" title=""${tag}"">${tag}</a>");
if (length != temp.Length)
{
keys.Remove(keys[i]);
}
length = temp.Length;
}
return temp;
});
}
2,页面中的调用示例
复制代码 代码示例:
<p><%=Tag.ReplaceTextTag(Tag.Contents)%></p>