Advertisement
uwekeim

Convert simple plain text to HTML

Aug 3rd, 2016
250
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 0.88 KB | None | 0 0
  1. // Converts single line breaks to BR tags, multiple line breaks to P tags. Does nothing more.
  2. public static string PlainTextToHtml(string text)
  3. {
  4.     if (string.IsNullOrWhiteSpace(text)) return text?.Trim();
  5.     text = text.Trim();
  6.  
  7.     // Remove blanks from otherwise completely empty lines.
  8.     text = Regex.Replace(text, @"^\s+$", string.Empty, RegexOptions.Multiline);
  9.  
  10.     text = text.Replace("\r\n", "\r");
  11.     text = text.Replace("\n", "\r");
  12.     text = text.Replace("\r", "\r\n");
  13.  
  14.     // Codense multiple blank lines.
  15.     text = Regex.Replace(text, "\n{3,}", Environment.NewLine + Environment.NewLine);
  16.  
  17.     text = HttpUtility.HtmlEncode(text);
  18.  
  19.     text = text.Replace("\r\n", "\r");
  20.     text = text.Replace("\n", "\r");
  21.  
  22.     text = text.Replace("\r\r", @"</p><p>");
  23.  
  24.     text = text.Replace("\r", @"<br>");
  25.  
  26.     text = @"<p>" + text + @"</p>";
  27.  
  28.     return text;
  29. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement