For some HTML tags, you can just do a simple string.Replace
. BBCode is in many ways just a 1:1, tag-for-tag mapping, for example <b>
and </b>
mapping to [B]
and [/B]
respectively. So that's easily accomplished with just:
html.Replace("<b>", "[b]").Replace("</b>", "[/b]")
If it's really dead-simple HTML, and you don't mind the performance impact and code ugliness of doing this tag-by-tag, go for it. But beware of cross-site scripting vulnerabilities, if you plan to display the resulting BBCode on a web page somewhere; this is nowhere near good enough for sanitization.
But don't even bother trying to use regular expressions to sanitize the HTML and do automatic replacement of all tags. The <img>
tag, for instance, looks completely different in HTML vs. BBCode. In HTML it's <img src="..."/>
(trailing slash is optional) and in BBCode it's [IMG]...[/IMG]
. Doing this with regex is... well, let's just say sub-optimal.
Regular expressions are designed for regular languages, and HTML is not a regular language, it's a context-free language. Consider using an actual HTML parser instead like the HTML Agility Pack. Then you can descend the DOM tree, whitelist the elements you want, and map them to BBCode or anything else however you like.