将普通字符串格式化为HTML C#

本文介绍了一种将普通文本转换成HTML的方法,支持格式化文本并自动识别URL与Email地址,将其转化为带有超链接的HTML格式。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

/// <summary>
    /// 将普通字符串格式化为HTML
    /// </summary>
    /// <param name="textStr">所要格式化的字符串</param>
    /// <param name="spotUrlEmail">是否自动识别"http://"或"https://"开头的URL和Email地址,识别出来的URL和Email将会自动加上超链接</param>
    /// <returns>格式化后的HTML代码</returns>
    public static string TextToHTML(string textStr, bool spotUrlEmail)
    {
        StringBuilder html = new StringBuilder(textStr);

        //html.Replace("&", "&amp;");   //2006-4-26修改。不对"&"进行转义了,不然无法处理好多个QueryString的URL
        html.Replace(" ", " &nbsp;"); //两个空格才转义,是为了较好处理带QueryString的URL后接空格的情况
        html.Replace("<", "&lt;");
        html.Replace(">", "&gt;");
        html.Replace("/"", "&quot;");
        html.Replace("/n", "<br />"); //IE中的换行为"/r/n",FF中为"/n"

        if (spotUrlEmail)
        {
            int offset;

            Regex linkRegex = new Regex("(http(s)?://)([//w-]+//.)+[//w-]+(/[//w-./?&%=]*)?");
            MatchCollection linkMatches = linkRegex.Matches(html.ToString());
            offset = 0;
            foreach (Match match in linkMatches)
            {
                string linkHead = string.Format("<a href=/"{0}/">", match.Value);

                html.Insert(match.Index + offset, linkHead);
                offset += linkHead.Length;

                html.Insert(match.Index + match.Length + offset, "</a>");
                offset += 4;
            }

            Regex emailRegex = new Regex("//w+([-+.']//w+)*@//w+([-.]//w+)*//.//w+([-.]//w+)*");
            MatchCollection emailMatches = emailRegex.Matches(html.ToString());
            offset = 0;
            foreach (Match match in emailMatches)
            {
                string emailHead = string.Format("<a href=/"mailto:{0}/">", match.Value);

                html.Insert(match.Index + offset, emailHead);
                offset += emailHead.Length;

                html.Insert(match.Index + match.Length + offset, "</a>");
                offset += 4;
            }
        }       

        return html.ToString();
    }

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值