是否可以像我尝试的那样使用 PHP 创建自定义标签
$str="[code] Code will goes here [/code]"
echo preg_replace("<div style='background-color:yellow;padding:5px'>$1</div>","/'[code'](.+)'['/code']/i",$str);
所以 [代码] 将成为我的自定义标签
你离得很近:
$str = "[code] Code will goes here [/code]";
//Pattern, Replacement, Original String
echo preg_replace(
"/'[code'](.*?)'['/code']/",
'<div style="background-color:yellow;padding:5px">$1</div>',
$str
);
是的,这最终是可能的。
你正在寻找的实际上是一个bbcode解析器,对吗?
如果是这种情况,请查看:StringParser_BBCode
试试这段代码:
$str = "[code] Code goes here, and it can safely contain <html> tags [/code]";
echo preg_replace_callback(
'#'[code'](.+?)'[/code']#i',
function($matches) {
return "<div style='background-color:yellow;padding:5px'>".htmlspecialchars(trim($matches[1]))."</div>";
},
$str
);
。或者对于 PHP <5.3:
function bbcode_code_tag($matches) {
return "<div style='background-color:yellow;padding:5px'>".htmlspecialchars(trim($matches[1]))."</div>";
}
$str = "[code] Code goes here, and it can safely contain <html> tags [/code]";
echo preg_replace_callback('#'[code'](.+?)'[/code']#i', 'bbcode_code_tag', $str);