tags:

views:

389

answers:

2

Hello! I need to convert html text into bbcodes. Where i can find how should i do this? For example, I convert links:

 regex = new Regex("<a href=\"(.+?)\">(.+?)</a>");
 htmlCode = regex.Replace(htmlCode, "[URL]$1[/URL]");

How can i convert all html tags in bbcodes (and replace to empty which isn't bb codes, tag P

+2  A: 

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?

Callum Rogers
oh,, no))i have clear xhtml. some tags: p,b,u,i,span,br,strong,h1-h6... thats all..)
Dmitriy
What do you mean by "clear xhtml"? You still need to (well, should) use a parser for elements like `<a href=....` which do not have a one to one mapping with BBcode.
Callum Rogers
i have clear link: only <a href="xx">name</a> only this. other i can lost
Dmitriy
If it is only `<a href="xx">name</a>` and is _always in that exact format_ then you could use a regex. It would be quicker than the DOM tree method.
Callum Rogers
A: 

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.

Aaronaught