You can add more bbcode tags just by calling a function within the class.
Code: Select all
<?php
class BBcode
{
private $functions = Array();
public function __construct()
{
self::addHook( "b", create_function( '$a,$v', 'return "<b>{$v}</b>";' ) );
self::addHook( "i", create_function( '$a,$v', 'return "<i>{$v}</i>";' ) );
self::addHook( "u", create_function( '$a,$v', 'return "<u>{$v}</u>";' ) );
self::addHook( "strike", create_function( '$a,$v', 'return "<span style=\"text-decoration:line-through;\">{$v}</span>";' ) );
}
public function parse( $text )
{
$x = true;
while( $x )
{
if( preg_match( "/\[([^=]*)(.*)\](.*)\[\/\\1\]/mU", $text ) )
{
$text = preg_replace( "/\[([^=]*)(.*)\](.*)\[\/\\1\]/emU", "self::run( \"$1\", \"$2\", \"$3\" )", $text );
}
else
{
return $text;
}
}
}
public function addHook( $bb, $function_name )
{
if( function_exists( $function_name ) )
{
$this->functions[ $bb ] = $function_name;
}
else
{
return FALSE;
}
}
private function run( $bb, $attr, $value )
{
if( isset( $this->functions[ $bb ] ) )
{
$ret = call_user_func( $this->functions[ $bb ], $attr, $value );
if( $ret != FALSE )
{
return $ret;
}
else
{
return "[{$bb}".(($attr!="")?$attr:"")."]{$value}[/{$bb}]";
}
}
else
{
return "[{$bb}".(($attr!="")?$attr:"")."]{$value}[/{$bb}]";
}
}
}
?>
Code: Select all
<?php
$BBcode = new BBcode();
$BBcode->addHook( "big", create_function( '$a,$v', 'return "<span style=\"font-size:50px;\">{$v}</span>";' ) );
echo $BBcode->parse( "[big]My Big Text[/big]" );
?>
Code: Select all
[img=200x300]http://mysite/myimage.jpg[/img]
Code: Select all
...( "=200x300", "http://mysite/myimage.jpg" );
Code: Select all
$BBcode = new BBcode();
function BBcode_img( $attr, $value )
{
if( preg_match( "/\A\=([0-9]*)\x([0-9]*)\Z/", $attr )
{
preg_replace( "/\A\=([0-9]*)\x([0-9]*)\Z/e", "$xy = Array( \"$1\", \"$2\" );", $attr );
return "<img src=\"{$value}\" width=\"{$xy[0]}\" height=\"{$xy[1]}\" alt=\"\" />";
}
else
{
if( $value != "" )
{
return "<img src=\"{$value}\" alt=\"\" />";
}
else
{
return FALSE;
}
}
}
$BBcode->addHook( "img", "BBcode_img" );
$BBcode->parse( "[img=200x300]http://mysite/myimage.jpg[/img]" );