Convert BBCode to HTML

http://www.dreamincode.net/code/snippet2661.htm

/*
* A method to convert BBCode to HTML
* Author: Danny Battison
* Contact: gabehabe@googlemail.com
*/

/// <summary>
/// A method to convert basic BBCode to HTML
/// </summary>
/// <param name="str">A string formatted in BBCode</param>
/// <returns>The HTML representation of the BBCode string</returns>
public string ConvertBBCodeToHTML (string str)
{
Regex exp;
// format the bold tags: [b][/b]
// becomes: <strong></strong>
exp = new Regex(@"\[b\](.+?)\[/b\]");
str = exp.Replace(str, "<strong>$1</strong>");

// format the italic tags: [i][/i]
// becomes: <em></em>
exp = new Regex(@"\[i\](.+?)\[/i\]");
str = exp.Replace(str, "<em>$1</em>");

// format the underline tags: [u][/u]
// becomes: <u></u>
exp = new Regex(@"\[u\](.+?)\[/u\]");
str = exp.Replace(str, "<u>$1</u>");

// format the strike tags: [s][/s]
// becomes: <strike></strike>
exp = new Regex(@"\[s\](.+?)\[/s\]");
str = exp.Replace(str, "<strike>$1</strike>");

// format the url tags: [url=www.website.com]my site[/url]
// becomes: <a href="www.website.com">my site</a>
exp = new Regex(@"\[url\=([^\]]+)\]([^\]]+)\[/url\]");
str = exp.Replace(str, "<a href=\"$1\">$2</a>");

// format the img tags: [img]www.website.com/img/image.jpeg[/img]
// becomes: <img src="www.website.com/img/image.jpeg" />
exp = new Regex(@"\[img\]([^\]]+)\[/img\]");
str = exp.Replace(str, "<img src=\"$1\" />");

// format img tags with alt: [img=www.website.com/img/image.jpeg]this is the alt text[/img]
// becomes: <img src="www.website.com/img/image.jpeg" alt="this is the alt text" />
exp = new Regex(@"\[img\=([^\]]+)\]([^\]]+)\[/img\]");
str = exp.Replace(str, "<img src=\"$1\" alt=\"$2\" />");

//format the colour tags: [color=red][/color]
// becomes: <font color="red"></font>
// supports UK English and US English spelling of colour/color
exp = new Regex(@"\[color\=([^\]]+)\]([^\]]+)\[/color\]");
str = exp.Replace(str, "<font color=\"$1\">$2</font>");
exp = new Regex(@"\[colour\=([^\]]+)\]([^\]]+)\[/colour\]");
str = exp.Replace(str, "<font color=\"$1\">$2</font>");

// format the size tags: [size=3][/size]
// becomes: <font size="+3"></font>
exp = new Regex(@"\[size\=([^\]]+)\]([^\]]+)\[/size\]");
str = exp.Replace(str, "<font size=\"+$1\">$2</font>");

// lastly, replace any new line characters with <br />
str = str.Replace("\r\n", "<br />\r\n");

return str;
}

原文地址:https://www.cnblogs.com/daoxuebao/p/2503496.html