不記得在哪看過這個,挺實用的 ...
不記得在哪看過這個,挺實用的
/// <summary> /// 將html文本轉化為 文本內容方法TextNoHTML /// </summary> /// <param name="Htmlstring">HTML文本值</param> /// <returns></returns> public string TextNoHTML(string Htmlstring) { //刪除腳本 Htmlstring = Regex.Replace(Htmlstring, @"<script[^>]*?>.*?</script>", "", RegexOptions.IgnoreCase); //刪除HTML Htmlstring = Regex.Replace(Htmlstring, @"<(.[^>]*)>", "", RegexOptions.IgnoreCase); Htmlstring = Regex.Replace(Htmlstring, @"([/r/n])[/s]+", "", RegexOptions.IgnoreCase); Htmlstring = Regex.Replace(Htmlstring, @"-->", "", RegexOptions.IgnoreCase); Htmlstring = Regex.Replace(Htmlstring, @"<!--.*", "", RegexOptions.IgnoreCase); Htmlstring = Regex.Replace(Htmlstring, @"&(quot|#34);", "/", RegexOptions.IgnoreCase); Htmlstring = Regex.Replace(Htmlstring, @"&(amp|#38);", "&", RegexOptions.IgnoreCase); Htmlstring = Regex.Replace(Htmlstring, @"&(lt|#60);", "<", RegexOptions.IgnoreCase); Htmlstring = Regex.Replace(Htmlstring, @"&(gt|#62);", ">", RegexOptions.IgnoreCase); Htmlstring = Regex.Replace(Htmlstring, @"&(nbsp|#160);", " ", RegexOptions.IgnoreCase); Htmlstring = Regex.Replace(Htmlstring, @"&(iexcl|#161);", "/xa1", RegexOptions.IgnoreCase); Htmlstring = Regex.Replace(Htmlstring, @"&(cent|#162);", "/xa2", RegexOptions.IgnoreCase); Htmlstring = Regex.Replace(Htmlstring, @"&(pound|#163);", "/xa3", RegexOptions.IgnoreCase); Htmlstring = Regex.Replace(Htmlstring, @"&(copy|#169);", "/xa9", RegexOptions.IgnoreCase); Htmlstring = Regex.Replace(Htmlstring, @"&#(/d+);", "", RegexOptions.IgnoreCase); //替換掉 < 和 > 標記 Htmlstring = Htmlstring.Replace("<", ""); Htmlstring = Htmlstring.Replace(">", ""); Htmlstring = Htmlstring.Replace("\r\n", ""); Htmlstring = Htmlstring.Replace("\r", ""); Htmlstring = Htmlstring.Replace("\n", ""); //返回去掉html標記的字元串 return Htmlstring; }
/// <summary> /// 獲取Img的路徑 /// </summary> /// <param name="htmlText">Html字元串文本</param> /// <returns>以數組形式返回圖片路徑</returns> public static string[] GetHtmlImageUrlList(string htmlText) { Regex regImg = new Regex(@"<img\b[^<>]*?\bsrc[\s\t\r\n]*=[\s\t\r\n]*[""']?[\s\t\r\n]*(?<imgUrl>[^\s\t\r\n""'<>]*)[^<>]*?/?[\s\t\r\n]*>", RegexOptions.IgnoreCase); //新建一個matches的MatchCollection對象 保存 匹配對象個數(img標簽) MatchCollection matches = regImg.Matches(htmlText); int i = 0; string[] sUrlList = new string[matches.Count]; //遍歷所有的img標簽對象 foreach (Match match in matches) { //獲取所有Img的路徑src,並保存到數組中 sUrlList[i++] = match.Groups["imgUrl"].Value; } return sUrlList; }