你使用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 的内容。然后从 db 中获取所有对应的名称。
$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);