Converts plain text into HTML, with line breaks and hyperlinks. - CSharp System

CSharp examples for System:String HTML

Description

Converts plain text into HTML, with line breaks and hyperlinks.

Demo Code


using System.Text.RegularExpressions;
using System.Text;
using System.Net;
using System;/*from w  ww  .  j a  v  a 2  s . c  o  m*/

public class Main{
        /// <summary>
        /// Converts plain text into HTML, with line breaks and hyperlinks.
        /// </summary>
        /// <param name="text"> The text to convert. </param>
        /// <returns> An HTML representation of the text. </returns>
        public static string ConvertTextToHtml(string text)
        {
            if (text == null)
                return string.Empty;

            // Newlines should be converted to <br> tags.
            var result = new StringBuilder();
            int start = 0;
            while (start < text.Length)
            {
                // Find the newline or linefeed.
                int newLineIndex = text.IndexOf(Environment.NewLine, start);
                newLineIndex = newLineIndex < 0 ? text.Length : newLineIndex;
                int lineFeedIndex = text.IndexOf('\n', start);
                lineFeedIndex = lineFeedIndex < 0 ? text.Length : lineFeedIndex;
                
                // Find the next URL.
                Match match = urlRegex.Match(text, start);
                Uri url = null;
                int urlIndex = text.Length;
                if (match.Success && Uri.TryCreate(match.Value, UriKind.Absolute, out url))
                    urlIndex = match.Index;

                // Encode the text.
                int nextEventIndex = Math.Min(Math.Min(newLineIndex, lineFeedIndex), urlIndex);
                result.Append(WebUtility.HtmlEncode(text.Substring(start, nextEventIndex - start)));
                start = nextEventIndex;

                if (newLineIndex < text.Length && newLineIndex < lineFeedIndex && newLineIndex < urlIndex)
                {
                    // Convert newline to <br>.
                    result.AppendLine("<br>");
                    start += 2;
                }
                else if (lineFeedIndex < text.Length && lineFeedIndex < newLineIndex && lineFeedIndex < urlIndex)
                {
                    // Convert linefeed to <br>.
                    result.AppendLine("<br>");
                    start += 1;
                }
                else if (urlIndex < text.Length && urlIndex < newLineIndex && urlIndex < lineFeedIndex)
                {
                    // Convert hyperlink to <a href="http://www.example.com" rel="nofollow">www.example.com</a>.
                    result.AppendFormat(@"<a href=""{0}"" rel=""nofollow"">{1}</a>", url, WebUtility.HtmlEncode(url.Host));
                    start += match.Length;
                }
            }
            return result.ToString();
        }
}

Related Tutorials