我有一个脚本,将注释中的所有BBCODES替换为HTML。
我已经成功地转换了所有简单的代码,除了用户名代码[user="max"]
,因为我需要获取更多的用户信息,如用户声誉&;从数据库查询用户在线状态。
$bbextended = array(
"/'[url](.*?)'['/url]/i" => "<a href='"http://$1'" title='"$1'">$1</a>",
"/'[user=(.*?)']/i" => "<div class='"user'"> <a href='"/user/$1'" title='"$1'">$1</a><span> $USER REPUTATION </span></div>",
);
foreach($bbextended as $match=>$replacement){
$bbtext = preg_replace($match, $replacement, $bbtext);
}
由于preg_replace
在其功能内替换匹配,我无法从数据库获取用户名以获取其他用户信息。
如果你使用preg_replace_callback
,你会发现你可以大规模扩展你的BBCode库。
的例子:
$bbextended = array(
"/'[url](.*?)'['/url]/i" => "<a href='"http://$1'" title='"$1'">$1</a>",
"/'[user=(.*?)']['/url]/i" => function($m) {
$foo = "bar";
return "<div class='"user'" <a href='"/user/".$m[1]."'" title='"".$m[1]."'">"
.$m[1]."</a><span> ".$foo." </span></div>";
}
);
foreach($bbextended as $match=>$replacement){
if( is_callable($replacement)) {
$bbtext = preg_replace_callback($match, $replacement, $bbtext);
}
else {
$bbtext = preg_replace($match, $replacement, $bbtext);
}
}