Forum Moderators: coopster

Message Too Old, No Replies

How to convert bbcode to html with php?

         

nirfun

1:31 pm on Jul 26, 2009 (gmt 0)

10+ Year Member



Hi,

I could not find a well-written function to convert bbcode to html (include lists)

anyone know a good way to convert bbcode to html?
Thanks

Nutter

3:29 pm on Jul 26, 2009 (gmt 0)

10+ Year Member



Regex should work

$string = preg_replace('/\[b\](.*)\[\/b\]/', '<strong>$1</strong>', $string);

nirfun

4:15 pm on Jul 26, 2009 (gmt 0)

10+ Year Member



Nutter,
parsing bbcode is not always that simple.
how would you parse lists?
[list]
  • item1
  • item2
    [/list]
  • rocknbil

    5:34 pm on Jul 26, 2009 (gmt 0)

    WebmasterWorld Senior Member 10+ Year Member



    $string = preg_replace('/\[b\](.*)\[\/b\]/', '<strong>$1</strong>', $string);

    This can be a little more efficient, and also .* means "zero or more of any character" so it will slurp up the [/b]. What you want is one or more of any character NOT a [ as below. Added case-insensitive, global, and multiline modifers . . .

    $tags = Array (
    'b' => 'strong',
    'i' => 'em',
    'bullet list' => 'ul',
    'ordered list' => 'ol',
    'list item' => 'li'
    );

    (or, if all the same, b=b, i=i, a simple list array.)

    foreach ($tags as $key=>$value) {
    $content = preg_replace('/\[$key\]([^\[]+)\[\/$key\]/img', "<$value>$1<\/$value>", $content);
    }

    This should also work for lists. The multiline modifier means treat the regex as multiple lines, the global means perform the replacement globally (may not be supported by PHP, or inherently global, if it dies on you remove the g.)

    When in doubt, analyze your regexp character by character:

    \[$key\] Begins with [$key]

    ( Begin storing the result in $1

    [^\[]+ Followed by one or more of any character NOT a [

    ) end saving of the pattern in $1

    \[\/$key\] ends with [/$key]

    img case insensitive, treat as multiple lines, apply regex globally

    [edited by: rocknbil at 5:44 pm (utc) on July 26, 2009]

    trillianjedi

    5:38 pm on Jul 26, 2009 (gmt 0)

    WebmasterWorld Senior Member 10+ Year Member



    I'm not sure why you're trying to reinvent the wheel?

    Have you looked at the bbcode.php file that comes with several open source forum applications ?