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;
});
}