Skip to content

Instantly share code, notes, and snippets.

@why404
Created May 7, 2009 03:22
Show Gist options
  • Save why404/107907 to your computer and use it in GitHub Desktop.
Save why404/107907 to your computer and use it in GitHub Desktop.
an example show you how to use php convert bbcode to html tags
<?php
/**
* bbcode2html
*
* @desc 用正则将帖子内容里面的UBBCODE转换为HTML标签显示
* @see http://php.net/manual/en/function.bbcode-create.php
* @param string $content
* @param boolean $nl2br
* @return string
*/
function bbcode2html($content, $nl2br = true)
{
//匹配模式
$pattern = array(
"/\[b\](.*)\[\/b\]/is",
"/\[u\](.*)\[\/u\]/is",
"/\[i\](.*)\[\/i\]/is",
"/\[quote\](.*)\[\/quote\]/is",
"/\[color=([^\[\<]+?)\](.*)\[\/color\]/is",
"/\[font=([^\[\<]+?)\](.*)\[\/font\]/is",
"/\[size=(\d+?)\](.*)\[\/size\]/is",
"/\[url\](.*)\[\/url\]/i",
"/\[url=(.*)\](.*)\[\/url\]/i",
"/\[flash=(\d+),(\d+)\]\s*([^\[\<\r\n]+?)\s*\[\/flash\]/i",
"/\[swf\]\s*([^\[\<\r\n]+?)\s*\[\/swf\]/i",
"/\[img\]\s*([^\[\<\r\n]+?)\s*\[\/img\]/i",
);
//替换格式
$replacement = array(
"<b>\\1</b>",
"<u>\\1</u>",
"<i>\\1</i>",
"<blockquote>\\1</blockquote>",
"<font color=\"\\1\">\\2</font>",
"<font face=\"\\1\">\\2</font>",
"<font size=\"\\1\">\\2</font>",
"<a href=\"\\1\" target=\"_blank\">\\1</a>",
"<a href=\"\\1\" target=\"_blank\">\\2</a>",
"<p><embed width=\"\\1\" height=\"\\2\" src=\"\\3\"></embed></p>",
"<p><embed width=\"500\" height=\"400\" src=\"\\1\"></embed></p>",
"<a href=\"\\1\" target=\"_blank\"><img src=\"\\1\" alt=\"\\1\" border=\"0\" /></a>",
);
//针对$content字符串进行$pattern规则的正则匹配并替换为$replacement所定义的格式
//可自行定义更多规则,保证一一对应就行了
$content = preg_replace($pattern, $replacement, $content);
//(不)换行, \n convert to <br />
$content = $nl2br === true ? nl2br($content) : $content;
return $content;
}
// try
$str = <<<EOF
[url=http://www.eoeandroid.com/faq.php?action=faq&id=5&messageid=18]http://www.eoeandroid.com/faq.php?action=faq&id=5&messageid=18[/url]
[url]http://www.eoeandroid.com/faq.php?action=faq&id=5&messageid=18[/url]
EOF;
echo bbcode2html($str);
// 另外一种方式可以参考 http://php.net/manual/en/function.bbcode-create.php
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment