Los Caballeros

"Sobre seguridad, programación, modding, frikismo, etc... "

PHP BBCode to HTML

Twitter icon Twitter icon
Este es un ejemplo de un conversor de BBCode a HTML, en este caso basicamente el 70% del codigo es para evitar bugs (como el bug ese que habia en los SMF's antiguos que se cerraban las comillas con tags dobles) xD...


<?php
$mensaje = "Aqui el BBCode a Convertir";
$mensaje = htmlentities($mensaje);
$marcainvisible = "<invisible>";
$tags = array("url","img","tube","code","color"); /* tags que no pueden tener otros tags dentro */
foreach($tags as $tag) {
if(preg_match_all("/\[".$tag."=(.*?)\[\/".$tag."\]/ism",$mensaje,$matches)) {
foreach($matches[1] as $valor) {
preg_match("/^(.*)](.*)$/ism",$valor,$matches);
$url = $matches[1];
$texto = htmlentities(preg_replace("/\[(.*?)\]/ism","[".$marcainvisible."$1".$marcainvisible."]",$matches[2]),ENT_QUOTES);
$valorlimpio = preg_replace("/\[/","%5B",$url);
$valorlimpio = htmlentities(preg_replace("/\]/","%5D",$valorlimpio),ENT_QUOTES);
$mensaje = str_ireplace("[".$tag."=".$valor."[/".$tag."]","[".$tag."=".$valorlimpio."]".$texto."[/".$tag."]",$mensaje);
}
}
if(preg_match_all("/\[".$tag."\](.*?)\[\/".$tag."\]/ism",$mensaje,$matches)) { foreach($matches[1] as $valor) {
$valorlimpio = preg_replace("/\[(.*?)\]/ism","[".$marcainvisible."$1".$marcainvisible."]",$valor);
$mensaje = str_ireplace("[".$tag."]".$valor."[/".$tag."]","[".$tag."]".$valorlimpio."[/".$tag."]",$mensaje);
} }
}
$a = array(
"/\[h2\](.*?)\[\/h2\]/ims","/\[code\](.+?)\[\/code\]/ims","/\[img\]\s*((https?|ftp):\/\/.+?)\[\/img\]/ims","/\[b\](.+?)\[\/b\]/ism","/\[url=((https?|ftp):\/\/.+?)\](.+?)\[\/url\]/ism","/\[url\]\s*((https?|ftp):\/\/.+?)\[\/url\]/ism"
);
$b = array(
"<font size=\"+1\">$1</font>","<b>$1</b>","<img src=\"$1\">","<div class=\"px\"><pre width=\"70\">$1</pre></div>","<a href=\"$1\" target=\"link\">$2</a>","<a href=\"$1\" target=\"link\">$1</a>"
);
$mensaje = str_replace($marcainvisible,"",preg_replace($a, $b, $mensaje));
print $mensaje;
?>



en este caso resumiendo la eliminacion del bug que comente al inicio, se utiliza un dato invisible (el tag "invisible") dentro de codigo que esta en htmlentities (de modo que seria el unico tag en todo el mensaje) para escapar tags bbcode que esten dentro de otros tags bbcode (tanto en propiedades como en los datos dentro de estos).