uwekeim icon

Convert simple plain text to HTML

uwekeim | PRO | 08/03/16 09:09:14 AM UTC | 0 ⭐ | 651 👁️ | Never ⏰ | []
C# |

880 B

|

None

|

0 👍

/

0 👎

// Converts single line breaks to BR tags, multiple line breaks to P tags. Does nothing more.
public static string PlainTextToHtml(string text)
{
    if (string.IsNullOrWhiteSpace(text)) return text?.Trim();
    text = text.Trim();
 
    // Remove blanks from otherwise completely empty lines.
    text = Regex.Replace(text, @"^\s+$", string.Empty, RegexOptions.Multiline);
 
    text = text.Replace("\r\n", "\r");
    text = text.Replace("\n", "\r");
    text = text.Replace("\r", "\r\n");
 
    // Codense multiple blank lines.
    text = Regex.Replace(text, "\n{3,}", Environment.NewLine + Environment.NewLine);
 
    text = HttpUtility.HtmlEncode(text);
 
    text = text.Replace("\r\n", "\r");
    text = text.Replace("\n", "\r");
 
    text = text.Replace("\r\r", @"</p><p>");
 
    text = text.Replace("\r", @"<br>");
 
    text = @"<p>" + text + @"</p>";
 
    return text;
}

Comments