我的文本转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();
    }
posted @ 2006-04-25 20:16  VeryDxZ  阅读(1909)  评论(1编辑  收藏  举报