给文章关键词加链接

在csdn上找到的一篇帖子,很有用 ,感谢回答的人.

private string RegReplace(Match m)
        {
            Dictionary<string, string> keywordList = o_Res.GetKeywordsByNews();//将数据库里查询到的关键词和相对应的url存放到Dictionary
            int index = -1;
            string temp = string.Empty;
            List<string> list = new List<string>();
            temp = m.Value;
            foreach (var tag in keywordList)
            {
                index = temp.IndexOf(tag.Key);
                if (index > -1)
                {
                    list.Add(tag.Key);
                    temp = temp.Substring(0, index) + "<a target='_blank' href="+tag.Value+">" + tag.Key + "</a>" + temp.Substring(index + tag.Key.Length);
                }
            }
            foreach (string s in list)
            {
                keywordList.Remove(s);
            }
            list.Clear();
            return temp;
        }

//调用
Regex reg = new Regex(@"(?:^|(?<!<(?:a|pre)\b(?>[^<>]*))>)(?>[^<>]*)(?:<|$)", RegexOptions.IgnoreCase | RegexOptions.Compiled);
            string result = reg.Replace(model.InfoContent, RegReplace);
            return result;//最后得到的文章

 

posted on 2013-11-21 17:41  刘阿毛  阅读(211)  评论(0编辑  收藏  举报

导航