1

Please am creating a wap forum and I want the admin to be able to add bbcodes from database named mycodes with columns: id, name, code, html

Row1
Name: bold
Code: \[b\](.*?)\[/b]
Html: < b >$1< / b >

Row2
Name: undaline
Code: \[u\](.*?)\[/u]
Html: < u >$1< / u >

When I use preg replace it worked only when I have one row, if I have more than one it won't work, it would only parse bold but not underline?

function myparse($text){
  $q = mysql_query("SELECT * FROM mycodes");
  while($row = mysql_fetch_array($q)) {
    $code=$row['code'];
    $html=$row['html']
    $Result=preg_replace('#'.$code.'#is', $html, $text);
    return $result;
  }
}

myparse("hey am [b]bold[/b] but he is [u]undalined[/u]");
marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
Trapcode
  • 113
  • 1
  • 8
  • Where does `$row` come from? If you want to apply multiple expressions I would expect to see a loop of some kind. – Ja͢ck Oct 24 '12 at 10:07

3 Answers3

1

Why re-invent the wheel:

http://www.christian-seiler.de/projekte/php/bbcode/index_en.html (also has links to some alternatives)

Or even the PECL lib: http://uk1.php.net/manual/en/book.bbcode.php

Brian
  • 8,418
  • 2
  • 25
  • 32
0

I don't see anything in your myparse function that loops through your rows of codes. So based on your current code you'll need a loop to call preg_replace multiple times:

function myparse($text){
    // Loop through rows (this might be a database or whatever stores your rows.
    // Since your code doesn't tell us I'll assume it's an array for now
    foreach ($rows as $row) {
        $code=$row['code'];
        $html=$row['html'];
        $Result=preg_replace('#'.$code.'#is', $html, $text);
    }
}
davidethell
  • 11,708
  • 6
  • 43
  • 63
0

You have couple of errors in your code. Correct function should be like this:

function myparse($text){
    $q = mysql_query("SELECT * FROM mycodes");
    while($row = mysql_fetch_array($q)) {
        $code=$row['code'];
        $html=$row['html']
        $text=preg_replace('#'.$code.'#is', $html, $text);
    }
    return $text;
}

In your code - only first line in mycodes is actually used.

Oleg Liski
  • 563
  • 4
  • 15