首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 开发语言 > C++ >

求算法,依照一定的规则替换字符串

2012-08-07 
求算法,按照一定的规则替换字符串希望可以实现一个算法,自动查找代码里的所有标签,并替换为html标签,必需

求算法,按照一定的规则替换字符串
希望可以实现一个算法,自动查找代码里的所有标签,并替换为html标签,必需用c++实现.
string codeToHtml(char *sCode); //传入代码字符串,返回html字符串


例1:[size=5]文本[/size]
需要转为
<font size="5">文本<font>

例2:
[color=black]这里是文本[/color]
需要转为
<font color="black">这里是文本</font>

例3:
[img]aa.jpg[/img]
需要转为
<src img="aa.jpg"/>


下面是原php代码的算法,有没高手可以转为C++的

PHP code
$message = str_replace(array(            '[/color]', '[/backcolor]', '[/size]', '[/font]', '[/align]', '[b]', '[/b]', '[s]', '[/s]', '[hr]', '[/p]',            '[i=s]', '[i]', '[/i]', '[u]', '[/u]', '[list]', '[list=1]', '[list=a]',            '[list=A]', "\r\n[*]", '[*]', '[/list]', '[indent]', '[/indent]', '[/float]'            ), array(            '</font>', '</font>', '</font>', '</font>', '</div>', '<strong>', '</strong>', '<strike>', '</strike>', '<hr class="l" />', '</p>', '<i class="pstatus">', '<i>',            '</i>', '<u>', '</u>', '<ul>', '<ul type="1" class="litype_1">', '<ul type="a" class="litype_2">',            '<ul type="A" class="litype_3">', '<li>', '<li>', '</ul>', '<blockquote>', '</blockquote>', '</span>'            ), preg_replace(array(            "/\[color=([#\w]+?)\]/i",            "/\[color=(rgb\([\d\s,]+?\))\]/i",            "/\[backcolor=([#\w]+?)\]/i",            "/\[backcolor=(rgb\([\d\s,]+?\))\]/i",            "/\[size=(\d{1,2}?)\]/i",            "/\[size=(\d{1,2}(\.\d{1,2}+)?(px|pt)+?)\]/i",            "/\[font=([^\[\<]+?)\]/i",            "/\[align=(left|center|right)\]/i",            "/\[p=(\d{1,2}|null), (\d{1,2}|null), (left|center|right)\]/i",            "/\[float=left\]/i",            "/\[float=right\]/i"            ), array(            "<font color=\"\\1\">",            "<font style=\"color:\\1\">",            "<font style=\"background-color:\\1\">",            "<font style=\"background-color:\\1\">",            "<font size=\"\\1\">",            "<font style=\"font-size:\\1\">",            "<font face=\"\\1\">",            "<div align=\"\\1\">",            "<p style=\"line-height:\\1px;text-indent:\\2em;text-align:\\3\">",            "<span style=\"float:left;margin-right:5px\">",            "<span style=\"float:right;margin-left:5px\">"            ), $message));


[解决办法]
提醒:解决字符串扫描替换问题的时候:正则表达式不是万能的;有限状态自动机才是万能的。
参考
《编译原理》词法分析 有限状态自动机
[解决办法]
这个问题搁在哪种语言里也是用正则,就是替换BBCODE而已。

先htmlspecialchars,然后正则换掉BBCODE。

下个PCRE库翻一翻接口就行了,PHP的preg就是PCRE库封装的:http://pcre.org/

热点排行