C#自动给文章关键字加链接实现代码
程序员文章站
2024-02-19 21:45:58
主要做的是,文章中的关键字标签加上链接,网上也有很多解决办法,自己整理以便后续在用。
效果如图:
下面是代码:
复制代码 代码如下:///
/// <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;
});
}
主要做的是,文章中的关键字标签加上链接,网上也有很多解决办法,自己整理以便后续在用。
效果如图:
下面是代码:
复制代码 代码如下:
/// <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 />
上一篇: jquery实现表格行拖动排序