Language: C#
Display HTML with Line Breaks
/// <summary> /// Fixes a plain text field for display as HTML by replacing carriage returns /// with the appropriate br and p tags for breaks. /// </summary> /// <param name="String Text">Input string</param> /// <returns>Fixed up string</returns> public static string DisplayMemo(string htmlText) { if (htmlText == null) return string.Empty; htmlText = htmlText.Replace("\r\n", "\r"); htmlText = htmlText.Replace("\n", "\r"); //HtmlText = HtmlText.Replace("\r\r","<p>"); htmlText = htmlText.Replace("\r", "<br />"); return htmlText; } /// <summary> /// Method that handles handles display of text by breaking text. /// Unlike the non-encoded version it encodes any embedded HTML text /// </summary> /// <param name="text"></param> /// <returns></returns> public static string DisplayMemoEncoded(string text) { if (text == null) return string.Empty; bool PreTag = false; if (text.IndexOf("<pre>") > -1) { text = text.Replace("<pre>", "__pre__"); text = text.Replace("</pre>", "__/pre__"); PreTag = true; } // fix up line breaks into <br><p> text = DisplayMemo(HtmlEncode(text)); //HttpUtility.HtmlEncode(Text)); if (PreTag) { text = text.Replace("__pre__", "<pre>"); text = text.Replace("__/pre__", "</pre>"); } return text; } /// <summary> /// HTML-encodes a string and returns the encoded string. /// </summary> /// <param name="text">The text string to encode. </param> /// <returns>The HTML-encoded text.</returns> public static string HtmlEncode(string text) { if (text == null) return string.Empty; StringBuilder sb = new StringBuilder(text.Length); int len = text.Length; for (int i = 0; i < len; i++) { switch (text[i]) { case '<': sb.Append("<"); break; case '>': sb.Append(">"); break; case '"': sb.Append("""); break; case '&': sb.Append("&"); break; default: if (text[i] > 159) { // decimal numeric entity sb.Append("&#"); sb.Append(((int)text[i]).ToString(CultureInfo.InvariantCulture)); sb.Append(";"); } else sb.Append(text[i]); break; } } return sb.ToString(); }
Tags:
Report Abuse
Subscribe
Discuss
What's new
What is it
New Snippet
Recent Snippets
My Snippets
Web Code
Search

