C#实现的html内容截取
C#实现的html内容截断,得到文章列表中的摘要信息。一般博客的首页只显示文章的摘要,点击标题进入以后查看全文。
下面是C#实现的html内容截断,获取html文章内容的摘要。效果还可以。效果参看web编程网。
using System.Collections.Generic; public class Tool{ /// <summary> /// 删除标签 /// </summary> /// <param name="tags"></param> /// <param name="tag"></param> private static void RemoveTag(List<string> tags, string tag) { for (int i = tags.Count - 1; i >= 0; i--) if (tags[i].IndexOf(tag) == 1) { tags.RemoveAt(i); break; } } /// <summary> /// 按文本内容长度截取HTML字符串(支持截取带HTML代码样式的字符串) /// </summary> /// <param name="html">将要截取的字符串参数</param> /// <param name="len">截取的字节长度</param> /// <param name="endString">字符串末尾补上的字符串</param> /// <returns>返回截取后的字符串</returns> public static string HTMLSubstring(string html, int len, string endString) { string r = ""; if (!string.IsNullOrEmpty(html) && html.Length > len) { MatchCollection mcentiry, mchtmlTag; List<string> inputHTMLTag = new List<string>(); string tmpValue, nowtag, losetag; int rWordCount = 0, wordNum = 0, i = 0; Regex rxSingle = new Regex("^<(br|hr|img|input|param|meta|link|wbr)", RegexOptions.Compiled | RegexOptions.IgnoreCase)//是否单标签正则 , rxEndTag = new Regex("</[^>]+>", RegexOptions.Compiled)//是否结束标签正则 , rxTagName = new Regex("</?([a-z\\d]+)[^>]*>", RegexOptions.Compiled | RegexOptions.IgnoreCase)//获取标签名正则 , rxHtmlTag = new Regex("<[^>]+>", RegexOptions.Compiled)//html标签正则 , rxEntity = new Regex("&[a-z]{1,9};", RegexOptions.Compiled | RegexOptions.IgnoreCase)//实体正则 , rxEntityReverse = new Regex("§", RegexOptions.Compiled)//反向替换实体正则 ; html = html.Replace("§", "§");//替换字符§为他的实体“§”,以便进行下一步替换 mcentiry = rxEntity.Matches(html);//收集实体对象到匹配数组中 html = rxEntity.Replace(html, "§");//替换实体为特殊字符§,这样好控制一个实体占用一个字符 mchtmlTag = rxHtmlTag.Matches(html);//收集html标签到匹配数组中 string[] arrWord = rxHtmlTag.Split(html);//拆分 wordNum = arrWord.Length; //获取指定内容长度及HTML标签 for (; i < wordNum; i++) { if (rWordCount + arrWord[i].Length >= len) r += arrWord[i].Substring(0, len - rWordCount) + endString; else r += arrWord[i]; rWordCount += arrWord[i].Length;//计算已经获取到的字符长度 if (rWordCount >= len) break; //搜集已经添加的非单标签,以便封闭HTML标签对 if (i < wordNum - 1) { tmpValue = mchtmlTag[i].Value.ToLower(); if (!rxSingle.IsMatch(tmpValue)) { //不是单标签 if (rxEndTag.IsMatch(tmpValue) && inputHTMLTag.Count > 0) { nowtag = rxTagName.Match(tmpValue).Groups[1].Value.ToLower(); losetag = rxTagName.Match(inputHTMLTag[inputHTMLTag.Count - 1]).Groups[1].Value.ToLower(); inputHTMLTag.RemoveAt(inputHTMLTag.Count - 1); if (nowtag != losetag) { RemoveTag(inputHTMLTag, nowtag); r += "</" + losetag + ">"; } } else inputHTMLTag.Add(tmpValue); } r += tmpValue; } } //替换回实体 for (i = 0; i < mcentiry.Count; i++) r = rxEntityReverse.Replace(r, mcentiry[i].Value, 1); //封闭标签 for (i = inputHTMLTag.Count - 1; i >= 0; i--) r += "</" + rxTagName.Match(inputHTMLTag[i].ToString()).Groups[1].Value + ">"; } else r = html; return r; } }
相关文章
加支付宝好友偷能量挖...
原创文章,转载请注明出处:C#实现的html内容截取