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]");
1
  • Where does $row come from? If you want to apply multiple expressions I would expect to see a loop of some kind. Commented Oct 24, 2012 at 10:07

3 Answers 3

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: https://www.php.net/manual/en/book.bbcode.php

Sign up to request clarification or add additional context in comments.

Comments

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);
    }
}

Comments

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.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.