PHP Velho Oeste 2024

bbcode_create

(PECL bbcode >= 0.9.0)

bbcode_createCrea un resource de BBCode

Descripción

bbcode_create ([ array $bbcode_initial_tags = NULL ] ) : resource

Esta función retorna un nuevo resource de BBCode usado para analizar strings BBCode.

Parámetros

bbcode_initial_tags

Un array asociativo que contiene el nombre de la etiqueta como clave y los parámetros requeridos para analizar correctamente el BBCode por su valor. Se soportan los siguientes pares clave/valor:

  • flags opcional - un set de flags basado en las constantes BBCODE_FLAGS_*.
  • type requerido - un int indicando el tipo de etiqueta. Usar las constantes BBCODE_TYPE_*.
  • open_tag requerido - el string HTML usado para reemplazar a la etiqueta de apertura.
  • close_tag requerido - el string HTML usado para reemplazar a la etiqueta de cierre.
  • default_arg opcional - usar este valor como el argumento por defecto si no se indica uno y tag_type es de tipo OPTARG.
  • content_handling opcional - proporciona la llamada de retorno usada para modificar el contenido. La Notación Orientada a Objetos soportada únicamente desde 0.10.1 El prototipo para la llamada de retorno es: string nombre(string $contenido, string $argumento)
  • param_handling opcional - proporciona la llamada de retorno usada para la modificación del argumento. La Notación Orientada a Objetos soportada únicamente desde 0.10.1 El prototipo para la llamada de retorno es: string nombre(string $contenido, string $argumento)
  • childs opcional - lista de hijos aceptados para la etiqueta. El formato de la lista es un string de valores separados por comas. Si la lista comienza con ! entonces es la lista de hijos no permitidos para la etiqueta.
  • parent opcional - lista de padres aceptados para la etiqueta. El formato de la lista es un string de valores separados por comas.

Valores devueltos

Retorna un resource BBCode_Container

Ejemplos

Ejemplo #1 Ejemplo de bbcode_create()

<?php
$arrayBBCode 
= array(
    
''=>         array('type'=>BBCODE_TYPE_ROOT,  'childs'=>'!i'),
    
'i'=>        array('type'=>BBCODE_TYPE_NOARG'open_tag'=>'<i>',
                    
'close_tag'=>'</i>''childs'=>'b'),
    
'url'=>      array('type'=>BBCODE_TYPE_OPTARG,
                    
'open_tag'=>'<a href="{PARAM}">''close_tag'=>'</a>',
                    
'default_arg'=>'{CONTENT}',
                    
'childs'=>'b,i'),
    
'img'=>      array('type'=>BBCODE_TYPE_NOARG,
                    
'open_tag'=>'<img src="''close_tag'=>'" />',
                    
'childs'=>''),
    
'b'=>        array('type'=>BBCODE_TYPE_NOARG'open_tag'=>'<b>',
                    
'close_tag'=>'</b>'),
);
$texto = <<<EOF
[b]Texto en negrita[/b]
[i]Texto en cursiva[/i]
[url]http://www.php.net/[/url]
[url=http://pecl.php.net/][b]Contenido[/b][/url]
[img]http://static.php.net/www.php.net/images/php.gif[/img]
[url=http://www.php.net/]
[img]http://static.php.net/www.php.net/images/php.gif[/img]
[/url]
EOF;
$BBHandler=bbcode_create($arrayBBCode);
echo 
bbcode_parse($BBHandler$texto);
?>

El resultado del ejemplo sería:

<b>Texto en negrita</b>
[i]Texto en cursiva[/i]
<a href="http://www.php.net/">http://www.php.net/</a>
<a href="http://pecl.php.net/"><b>Content Text</b></a>
<img src="http://static.php.net/www.php.net/images/php.gif" />
<a href="http://www.php.net/">
[img]http://static.php.net/www.php.net/images/php.gif[/img]
</a>

add a note add a note

User Contributed Notes 1 note

up
27
rothenbergxxx at gmail dot com
14 years ago
For those without the BBCode extension, here's a relatively elegant function to do the trick.
Keep in mind that if you're using XHTML and one of your users tries to overlap lags <b>Like <i>so</b></i>, it will invalidate your markup. Still working on an expression for this.

<?php
   
function bb_parse($string) {
       
$tags = 'b|i|size|color|center|quote|url|img';
        while (
preg_match_all('`\[('.$tags.')=?(.*?)\](.+?)\[/\1\]`', $string, $matches)) foreach ($matches[0] as $key => $match) {
            list(
$tag, $param, $innertext) = array($matches[1][$key], $matches[2][$key], $matches[3][$key]);
            switch (
$tag) {
                case
'b': $replacement = "<strong>$innertext</strong>"; break;
                case
'i': $replacement = "<em>$innertext</em>"; break;
                case
'size': $replacement = "<span style=\"font-size: $param;\">$innertext</span>"; break;
                case
'color': $replacement = "<span style=\"color: $param;\">$innertext</span>"; break;
                case
'center': $replacement = "<div class=\"centered\">$innertext</div>"; break;
                case
'quote': $replacement = "<blockquote>$innertext</blockquote>" . $param? "<cite>$param</cite>" : ''; break;
                case
'url': $replacement = '<a href="' . ($param? $param : $innertext) . "\">$innertext</a>"; break;
                case
'img':
                    list(
$width, $height) = preg_split('`[Xx]`', $param);
                   
$replacement = "<img src=\"$innertext\" " . (is_numeric($width)? "width=\"$width\" " : '') . (is_numeric($height)? "height=\"$height\" " : '') . '/>';
                break;
                case
'video':
                   
$videourl = parse_url($innertext);
                   
parse_str($videourl['query'], $videoquery);
                    if (
strpos($videourl['host'], 'youtube.com') !== FALSE) $replacement = '<embed src="http://www.youtube.com/v/' . $videoquery['v'] . '" type="application/x-shockwave-flash" width="425" height="344"></embed>';
                    if (
strpos($videourl['host'], 'google.com') !== FALSE) $replacement = '<embed src="http://video.google.com/googleplayer.swf?docid=' . $videoquery['docid'] . '" width="400" height="326" type="application/x-shockwave-flash"></embed>';
                break;
            }
           
$string = str_replace($match, $replacement, $string);
        }
        return
$string;
    }
?>

[EDIT BY danbrown AT php DOT net: Contains a bugfix provided by (ramonvandam AT gmail DOT com) on 04-SEP-09 to address an improperly-defined parameter.  Also contains a bugfix provided by (pompei2 AT gmail DOT com) on 15-FEB-10 to address improperly-closed tags.  Plus, contains another bugfix provided by (angad AT wootify DOT com) on 18-JUL-2011 to fix an issue where unsupported tags provided to the function could cause the script to time out.]
To Top