Parser de BBCODE en PHP


Pues programando un sitio web donde los usuarios usaran BBCODE para postear articulos hice un parser de BBCODE a HTML en PHP.

Las ventajas de usar BBCode son muchas, una de ellas es el facil aprendizaje, asi la gente no tiene que aprender HTML para publicar articulos.





Codigo de bbcode.php :

<?php
    class bbcode() {
   
    // Array de tags BBCODE, pueden añadir otras tags si quieren
    var $bbcode = array(
        '@\[(?i)h1\](.*?)\[/(?i)h1\]@si',
        '@\[(?i)h2\](.*?)\[/(?i)h2\]@si',
            '@\[(?i)b\](.*?)\[/(?i)b\]@si',
            '@\[(?i)i\](.*?)\[/(?i)i\]@si',
            '@\[(?i)u\](.*?)\[/(?i)u\]@si',
            '@\[(?i)img=(.*?)\](.*?)\[/(?i)img\]@si',
            '@\[(?i)url=(.*?)\](.*?)\[/(?i)url\]@si',
            '@\[(?i)code\](.*?)\[/(?i)code\]@si',
            '@\[(?i)color=\"(.*?)\"\](.*?)\[/(?i)color\]@si'
    );
       
    var $html = array(
        '<h2>\\1</h2>',
        '<h3>\\1</h3>',
            '<b>\\1</b>',
            '<i>\\1</i>',
            '<u>\\1</u>',
            '<img title="\\2" src="\\1" />',
            '<a href="\\1">\\2</a>',
            '<code>\\1</code>',
            '<span style="color: \\1;">\\2</span>'
    );
   
    function parser($texto) {
        // Bucle for que le hace la funcion htmlentities al array de BBCODE para evitar ataques XSS
        for($i = 0; $i<9; $i++) {
                $this->bbcode[$i] = htmlentities($this->bbcode[$i]);
        }
       
        // Pasamos el texto a htmlentities, tambien para evitar ataques XSS
        $texto = htmlentities($texto);
       
        // Reemplazamos el array BBCODE por el HTML
        $texto = preg_replace($this->bbcode , $this->html, $texto);
           
        //Reemplazamos los \n a <br />
          $texto = nl2br($texto);
         
          //Devolvemos el string HTML
          return $texto;
    }
    }
?>

Como se usa ?

Basicamente hacen un include del bbcode.php :

include("bbcode.php");
Declaran un objeto de la classe bbcode :

$variable = new bbcode();
Llaman a la funcion :

$variable->parser("Esto es un texto en [b]Negrita[/b], [i]Crusiva[/i] y [u]Subrayado[/i].");

En resumen :
<?php
        include("bbcode.php");
        $variable = new bbcode();
        $variable->parser("Esto es un texto en [b]Negrita[/b], [i]Crusiva[/i] [u]Subrayado[/i].");
?>

Comentarios

Entradas populares de este blog