Foliotek Developer Blog

Convert HTML to BBCode in C#

Here is a code snippet that will convert HTML into BBCode using C#.

I know you are not suppose to use regular expressions to manipulate HTML and that I should have used agility pack, but this was the quickest solution to write.
[sourcecode language='csharp']

public string FormatHtmlIntoBBCode(string desc)
{
desc = Regex.Replace (desc, @”
“, “[br]“, RegexOptions.IgnoreCase);
desc = Regex.Replace (desc, @”

]>”, “[ulist]“, RegexOptions.IgnoreCase);
desc = Regex.Replace (desc, @”“, “[/ulist]“, RegexOptions.IgnoreCase);
desc = Regex.Replace (desc, @” ]
>”, “[olist]“, RegexOptions.IgnoreCase);
desc = Regex.Replace (desc, @”“, “[/olist]“, RegexOptions.IgnoreCase);
desc = Regex.Replace (desc, @”6. “, “[]“, RegexOptions.IgnoreCase);
desc = Regex.Replace (desc, @”“, “”, RegexOptions.IgnoreCase);
desc = Regex.Replace (desc, @”“, “[b]“, RegexOptions.IgnoreCase);
desc = Regex.Replace (desc, @”>”, “[/b]“, RegexOptions.IgnoreCase);
desc = Regex.Replace (desc, @”
“, “[strong]“, RegexOptions.IgnoreCase);
desc = Regex.Replace (desc, @”“, “[/strong]“, RegexOptions.IgnoreCase);
desc = Regex.Replace (desc, @”“, “[u]“, RegexOptions.IgnoreCase);
desc = Regex.Replace (desc, @”“, “[/u]“, RegexOptions.IgnoreCase);
desc = Regex.Replace (desc, @”
“, “[i]“, RegexOptions.IgnoreCase);
desc = Regex.Replace (desc, @”“, “[/i]“, RegexOptions.IgnoreCase);
desc = Regex.Replace (desc, @”*“, “[em]“, RegexOptions.IgnoreCase);
desc = Regex.Replace (desc, @”“, “[/em]“, RegexOptions.IgnoreCase);
desc = Regex.Replace (desc, @”“, “[sup]“, RegexOptions.IgnoreCase);
desc = Regex.Replace (desc, @”“, “[/sup]“, RegexOptions.IgnoreCase);
desc = Regex.Replace (desc, @”“, “[sub]“, RegexOptions.IgnoreCase);
desc = Regex.Replace (desc, @”“, “[/sub]“, RegexOptions.IgnoreCase);
desc = Regex.Replace (desc, @”- - - - - -

]*>”, “[hr]“, RegexOptions.IgnoreCase);
desc = Regex.Replace (desc, @”“, “[strike]“, RegexOptions.IgnoreCase);
desc = Regex.Replace (desc, @”“, “[/strike]“, RegexOptions.IgnoreCase);
desc = Regex.Replace (desc, @”

“, “[h1]“, RegexOptions.IgnoreCase);

desc = Regex.Replace (desc, @”“, “[/h1]“, RegexOptions.IgnoreCase);
desc = Regex.Replace (desc, @”

“, “[h2]“, RegexOptions.IgnoreCase);

desc = Regex.Replace (desc, @”“, “[/h2]“, RegexOptions.IgnoreCase);
desc = Regex.Replace (desc, @”

“, “[h3]“, RegexOptions.IgnoreCase);

desc = Regex.Replace (desc, @”“, “[/h3]“, RegexOptions.IgnoreCase);
desc = Regex.Replace (desc, @” desc = Regex.Replace (desc, @"“, “[/url]“, RegexOptions.IgnoreCase);
desc = Regex.Replace (desc, @”‘>”, “‘]”, RegexOptions.IgnoreCase);

//match on image tags
var match = Regex.Matches(desc, @”!“, RegexOptions.IgnoreCase);
if(match.Count > 0)
desc = Regex.Replace (desc, match[0].ToString(), “[img]“+ match[0].Groups[1].Value + “[/img]“, RegexOptions.IgnoreCase);

return desc;
}
[/sourcecode]

There you have it. ?A simple piece of code that will convert a simple html block into BBcode.

**