Spesso capita di avere a che fare con forum e blog vari, tirando fuori post dal database a volte i post sono formattati col bbcode, e necessitano di una funzione che permetta di parsare il codice e trasformarlo in htm standard, ne ho fatta una oggi che serve proprio a questo scopo, ecco il codice:
public static string ParseBBCode(string textToReplace)
{
//DEFINISCO LA REGULAR EXPRESSION
Regex regEx;
// PARSO LE URL SENZA ANCORA
regEx = new Regex(@"\[url\]([^\]]+)\[\/url\]");
textToReplace = regEx.Replace(textToReplace, "<a href=\"$1\" target=\"_blank\">$1</a>");
//PARSO LE URL CON L'ANCORA
regEx = new Regex(@"\[url=([^\]]+)\]([^\]]+)\[\/url\]");
textToReplace = regEx.Replace(textToReplace, "<a href=\"$1\" target=\"_blank\">$2</a>");
//PARSO LE IMMAGINI
regEx = new Regex(@"\[img\]([^\]]+)\[\/img\]");
textToReplace = regEx.Replace(textToReplace, "<img src=\"$1\" />");
//PARSO IL TESTO IN BOLD
regEx = new Regex(@"\[b\](.+?)\[\/b\]");
textToReplace = regEx.Replace(textToReplace, "<b>$1</b>");
//PARSO IL TESTO IN CORSIVO
regEx = new Regex(@"\[i\](.+?)\[\/i\]");
textToReplace = regEx.Replace(textToReplace, "<i>$1</i>");
//PARSO IL TESTO SOTTOLINEATO
regEx = new Regex(@"\[u\](.+?)\[\/u\]");
textToReplace = regEx.Replace(textToReplace, "<u>$1</u>");
//PARSO LE DIMENSIONI DEI FONT
regEx = new Regex(@"\[size=([^\]]+)\]([^\]]+)\[\/size\]");
textToReplace = regEx.Replace(textToReplace, "<span style=\"font-size: $1px\">$2</span>");
//PARSO I COLORI DEL TESTO
regEx = new Regex(@"\[color=([^\]]+)\]([^\]]+)\[\/color\]");
textToReplace = regEx.Replace(textToReplace, "<span style=\"color: $1\">$2</span>");
return textToReplace;
}