How convert html to BBcode in C#

寵の児 提交于 2019-12-07 16:04:28

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.

Rather than use Regexs (which cannot ever ever ever parse HTML), try using HtmlAgilityPack to search down the DOM tree and change the relevant HTML tags into BBCode. Making a new valid BBCode document would seem to be the hardest part of this - maybe there is some library to help make valid BBCode markup somewhere?

I know your suppose to use a tool built for parsing the DOM aka HtmlAgilityPack but I needed something that could use the tools built into .net and not have to reference an external dll.

So I wrote a converter in c# that does it all through RegEx.

Here's my write-up http://www.foliotek.com/devblog/convert-html-to-bbcode-in-c/

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!