private void rc()
{
string str1 = "<img src=\"sss.jpg\" alt=\"网络技术网络;网络应用\">网络技术网络;网络应用 网络基本知识 <img src=\"sss.jpg\" alt=\"网络技术网络;网络应用\"><a href=\"http://www.stobar.cn/">网络技术网络;网络应用 网络基本知识</a>";
List<string> keys = new List<string>();
keys.Add("网络");
keys.Add("网络技术");
keys.Add("网络基本");
string result = keyAddUrl(str1, keys,"http://www.baidu.com/");
this.Label1.Text = result;
}
/// <summary>
/// 给关键字加链接,同一关键字只加一次
/// </summary>
/// <param name="src">源字符串</param>
/// <param name="keys">关键字泛型</param>
/// <param name="keys">链接地址</param>
/// <returns>替换后结果</returns>
private string keyAddUrl(string src, List<string> keys ,string URL)
{
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]) + @"|</?a\b).)*<a\b(?:(?!</?a\b).)*</a>)*(?:(?!" + Regex.Escape(keys[i]) + @"|</?a\b).)*)(?<tag>" + Regex.Escape(keys[i]) + @")", @"$1<a href="+URL+" target=\"_blank\" title=\"${tag}\">${tag}</a>");
if (length != temp.Length)
{
keys.Remove(keys[i]);
}
length = temp.Length;
}
return temp;
});
}