HtmlHelper操作Html帮助类库

检查是否有Html标签

格式化输出到页面的字符串,包括转换回车符

过滤掉所有的Html标签后的字符串


HtmlHelper类库源码

/// <summary>
/// 开发团队:yunjsonTeam
/// 官方主页:http://www.yunjson.com
/// </summary>
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web;
using System.Text.RegularExpressions;

namespace yunjsonTeamUtil.Helper
{
    public class HtmlHelper
    {
        /// <summary>
        /// 格式化输出到页面的字符串,包括转换回车符
        /// </summary>
        /// <param name="htmlstr">要格式化的字符串</param>
        /// <param name="replace">是否替换换行符</param>
        /// <returns>格式化后的字符串</returns>
        public static string FormatHtmlString(string htmlstr, bool replace)
        {
            if (string.IsNullOrEmpty(htmlstr)) return "";
            htmlstr = HttpContext.Current.Server.HtmlEncode(htmlstr);
            htmlstr = htmlstr.Replace(" ", "&nbsp;");
            if (replace) { htmlstr = htmlstr.Replace("\r\n", "<br />"); }
            return htmlstr;
        }

        public static string FormatHtmlString(string htmlstr)
        {
            htmlstr = HttpContext.Current.Server.HtmlEncode(htmlstr);
            htmlstr = htmlstr.Replace(" ", "&nbsp;");
            htmlstr = htmlstr.Replace("<", "&lt;");
            htmlstr = htmlstr.Replace(">", "&gt;");
            return htmlstr;
        }

        /// <summary>
        /// 返回过滤掉所有的Html标签后的字符串
        /// </summary>
        /// <param name="html">Html源码</param>
        /// <returns>过滤Html标签后的字符串</returns>
        public static string ClearAllHtml(string html)
        {
            string filter = "<[\\s\\S]*?>";
            if (Regex.IsMatch(html, filter))
            {
                html = Regex.Replace(html, filter, "");
            }
            filter = "[<>][\\s\\S]*?";
            if (Regex.IsMatch(html, filter))
            {
                html = Regex.Replace(html, filter, "");
            }
            return html;
        }

        /// <summary>
        /// 检查是否有Html标签
        /// </summary>
        /// <param name="html">Html源码</param>
        /// <returns>存在为True</returns>
        public static bool CheckHtml(string html)
        {
            string filter = "<[\\s\\S]*?>";

            if (Regex.IsMatch(html, filter))
            {
                return true;
            }
            filter = "[<>][\\s\\S]*?";
            if (Regex.IsMatch(html, filter))
            {
                return true;
            }
            return false;
        }
    }
}