您使用preg_replace_callback功能,
$bbcode = preg_replace_callback($match, function($matches){
// execute query
$query = "SELECT username FROM users WHERE id = '{$matches[1]}'";
// get user name
$username = $row['username']; // just for illustration.
// return formatted string.
return "<div class=\"quote\">$username said:<br />>$matches[2]</div>";
}, $str);
哦,有一個更好的方式,這樣做。爲他們每個人運行SQL查詢不是一個好主意。因此,首先獲取所有用戶ID一個內容。然後從數據庫中獲取所有相應的名稱。
$match = "/\[quote=(.*?)\](.*?)\[\/quote\]/is";
preg_match_all($match, $str, $matches);
$query = "SELECT id, username from tbl1 where id IN (".implode(",", $matches[1]).")";
// run the query. get all the row in a hash.
$hash[$row['id']] = $hash[$row['username']];
$bbcode = preg_replace_callback($match, create_function(
'$m',
'global $hash;return "<div class=\\"quote\\">{$hash[$m[1]]} said:<br />$m[2]</div>";'
), $str);
爲什麼你不使用BBCode分析器? – Gordon
喜歡什麼?我查了一下,但似乎無法找到任何看起來不錯的東西。 – user1989781
像[native one?](http://php.net/manual/en/book.bbcode.php)。 – Gordon