VB.net 2010 视频教程 VB.net 2010 视频教程 python基础视频教程
SQL Server 2008 视频教程 c#入门经典教程 Visual Basic从门到精通视频教程
当前位置:
首页 > c#编程 >
  • C#教程之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)
        {
            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 />


相关教程