zoukankan      html  css  js  c++  java
  • 我的文本转HTML加超链接函数

    以前曾经看到一个不错的文本转HTML的函数,可惜被我弄丢了。幸好还记得原理,今天决定自己写写。

    在要使用的.aspx的@Page中加入 ValidateRequest="false",使用到的namespace:System.Text,System.Text.RegularExpressions。

        /// <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();
        }
  • 相关阅读:
    XE8下安装IntraWeb 14.0.40和D7下安装IntraWeb 11.0.63破解版的正确方法
    网易博客打不开怎么办
    SQL SERVER 导入EXCEL的存储过程
    TMemoryStream、String与OleVariant互转
    【转载】Delphi Idhttp的get和post方法
    sqlserver得到行号
    Delphi 中的 XMLDocument 类详解(5)
    10款免费且开源的项目管理工具
    iOS开发者必备:九大设计类工具
    15个步骤创立技术公司,并收获千万用户(完结)
  • 原文地址:https://www.cnblogs.com/dxz/p/text_to_html.html
Copyright © 2011-2022 走看看