i want to build a forum and use bbcode.
i've studied the <code></code> problem when you have tag inside the code like in a comment
*i use [codex] instead of [ code ] (otherwise the post will use them as real tag 🙂
exemple:
[codex]
aaaaaaaaaaa
// comment [codex] comment
bbbbbbbbbbb
/ comment [/codex] /
ccccccccccc
/
[/codex]
**/
ddddddddddd
[/codex]
some text between 2 tag
[codex]
some other text
[/codex]
here is the code i use to be able to parse this sample string
function bbcode_prepare($text, $tag, $color)
{
// finding comment in text and modify commented tag
$pattern = array("/\/\*(.*?|\n)\*\//is","/\/\/.*?\n/is");
for ($x=0; $x<count($pattern); $x++)
{
$nb_matches = preg_match_all($pattern[$x], $text, $matches);
for ($i=0; $i<count($matches[0]); $i++)
{
$foo = str_replace(array("[$tag]","[/$tag]"), array("[ $tag ]", "[ /$tag ]"), $matches[0][$i]);
$text = str_replace($matches[0][$i], "<font color=orange>".$foo."</font>", $text);
}
}
// finding the tagged zone and apply style
$pattern = "/\[$tag\].*?\[\/$tag\]/is";
$nb_matches = preg_match_all($pattern, $text, $matches);
for ($i=0; $i<count($matches[0]); $i++)
{
$tagzone = trim(str_replace(array("[$tag]","[/$tag]"), array("",""), $matches[0][$i]));
$foo = str_replace($matches[0][$i], "<table border=1 cellspacing=0><tr><td><font color=$color>".$tagzone."</font></td></tr></table>", $matches[0][$i]);
$text = str_replace($matches[0][$i], $foo, $text);
}
$text = str_replace("</table>" . chr(13) . chr(10), "</table>", $text);
return $text;
}
$tmp = $_POST[message];
$tmp = strtr($tmp, get_html_translation_table(HTML_ENTITIES));
$tmp = eregi_replace(chr(32), " ", $tmp);
$tmp = eregi_replace(chr(9), " ", $tmp);
$tmp = bbcode_prepare($tmp, "code", "navy");
$tmp = eregi_replace(chr(13) . chr(10), "<br>", $tmp);
echo $tmp;
this seems to work well, probably not fully optimised for exceptions that can occur so.. i've do my best, i'm new to bbcode and regex
Any critique will be welcome
Thanks