BBCode Format Function
This function can be used in your scripts to use BBCode.
function bbcode_format ($str) {
$str = htmlentities($str);
$simple_search = array(
'/\[b\](.*?)\[\/b\]/is',
'/\[i\](.*?)\[\/i\]/is',
'/\[u\](.*?)\[\/u\]/is',
'/\[url\=(.*?)\](.*?)\[\/url\]/is',
'/\[url\](.*?)\[\/url\]/is',
'/\[align\=(left|center|right)\](.*?)\[\/align\]/is',
'/\[img\](.*?)\[\/img\]/is',
'/\[mail\=(.*?)\](.*?)\[\/mail\]/is',
'/\[mail\](.*?)\[\/mail\]/is',
'/\[font\=(.*?)\](.*?)\[\/font\]/is',
'/\[size\=(.*?)\](.*?)\[\/size\]/is',
'/\[color\=(.*?)\](.*?)\[\/color\]/is',
);
$simple_replace = array(
'$1',
'$1',
'$1',
'$2',
'$1',
'$2',
'',
'$2',
'$1',
'$2',
'$2',
'$2',
);
// Do simple BBCode's
$str = preg_replace ($simple_search, $simple_replace, $str);
// Do BBCode
$str = bbcode_quote ($str);
return $str;
}
function bbcode_quote ($str) {
$open = ''
;
$close = '';
// How often is the open tag?
preg_match_all ('/\[quote\]/i', $str, $matches);
$opentags = count($matches['0']);
// How often is the close tag?
preg_match_all ('/\[\/quote\]/i', $str, $matches);
$closetags = count($matches['0']);
// Check how many tags have been unclosed
// And add the unclosing tag at the end of the message
$unclosed = $opentags - $closetags;
for ($i = 0; $i < $unclosed; $i++) {
$str .= '';
}
// Do replacement
$str = str_replace ('[' . 'quote]', $open, $str);
$str = str_replace ('[/' . 'quote]', $close, $str);
return $str;
}
?>
November 2nd, 2005 at 11:51 pm
Very nice article. But shouldn’t this:
[quote]
$str = str_replace (’
‘, $close, $str);
[/quote]
be this:
[quote]
$str = str_replace (’[ quote]’, $open, $str);
$str = str_replace (’[ /quote’, $close, $str);
[/quote]
Note the superfluous space to prevent the bbcode from being interpreted as bbcode!
November 3rd, 2005 at 9:42 pm
You’re right, and I’ve fixed the code above. Thanks for letting me know!
January 15th, 2006 at 11:54 pm
[…] Codesnippets […]
February 5th, 2006 at 3:09 pm
hoho, looks like mine, doesn’t it ;)
but the second part is pretty neat to me, the idea of checking unclosed tags can be extended easily to all tags i suppose :)
March 5th, 2006 at 2:59 am
Hey I have a site and it posts info into the database but it can’t post html so I want to add bb codes to it and on the page that it shows the data it doesn’t replace [b]text[/b] into a bolded text. Can someone help me out.