I’m in the process of upgrading my site’s engine. The new version does not support bbcodes, and all my forum posts and articles are created using it.
I want to make a script to convert all text with bbdodes to html. But I’ve run into a problem and I’m not sure how to proceed. Please take a look at my code and suggest how I can improve it.
Functions:
function bbcodeconvert($text)
{
$text = " ".$text;
$bbcodes = array(
'[b]' => '<strong>',
'[/b]' => '</strong>'
);
foreach($bbcodes as $bbcode => $bbcodehtml)
{ $text = str_replace($bbcode,$bbcodehtml,$text); }
$bbcodes2 = array(
'\[img\]([^\';?([]*).(jpg|jpeg|gif|png)\[/img\]' => '<img src="\1.\2" alt="">',
'\[img=([^\';?([]*).(jpg|jpeg|gif|png)\]([^\[]*).(jpg|jpeg|gif|png)\[/img\]' => '<a href="\1.\2" data-lightbox="spic"><img src="\3.\4" alt=""></a>',
'\[youtube\]([^\([]*)\[/youtube\]' => '<iframe width="540" height="320" src="https://www.youtube.com/embed/\1?wmode=opaque" frameborder="0" allowfullscreen></iframe>',
'\[colleft\]([^\[]*)\[/colleft\]' => '<div class="colleft">\1</div>',
'\[colright\]([^\[]*)\[/colright\]' => '<div class="colright">\1</div>'
);
foreach($bbcodes2 as $bbcode => $bbcodehtml)
{ $text = preg_replace($bbcode,$bbcodehtml,$text); }
return(mb_substr($text,1));
}
function oldparse($text)
{
global $sys, $L;
$text = ' '.$text;
$code = array();
$unique_seed = $sys['unique'];
$ii = 5000;
$p1 = 1;
$p2 = 1;
while ($p1 > 0 && $p2 > 0 && $ii < 5031)
{
$ii++;
$p1 = mb_strpos($text, '[code]');
$p2 = mb_strpos($text, '[/code]');
if ($p2 > $p1 && $p1 > 0)
{
$key = '**'.$ii.$unique_seed.'**';
$code[$key]= mb_substr ($text, $p1 + 6, ($p2 - $p1) - 6);
$code_len = mb_strlen($code[$key]) + 13;
$code[$key] = str_replace('t',' ', $code[$key]);
$code[$key] = str_replace(' ', ' ', $code[$key]);
$code[$key] = str_replace(' ', ' ', $code[$key]);
$code[$key] = str_replace(
array('{', '<', '>' , ''', '"', "<!--", '$' ),
array('{', '<', '>', ''', '"', '"<!--"', '$' ),$code[$key]);
$code[$key] = "<div class="codetitle">".$L['bbcodes_code'].":</div><div class="code">".trim($code[$key])."</div>";
$text = substr_replace($text, $key, $p1, $code_len);
}
}
$text = sed_bbcode($text);
return(mb_substr($text, 1));
}
Execution example:
$sql = sql_query("SELECT some_text FROM forum_posts WHERE topicid='$s' LIMIT 1");
while ($row = sql_fetchassoc($sql)) {
$post_text = oldparse($row['some_text']);
}
$output = "Converted text:$post_text";
I have no problem with a first part where I use “str_replace”, but can’t figure out segment with “preg_replace” for more complicated bbcodes. Any suggestions?
Leks is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.