php中显示格式化的用户输入(二)
操作方法
- 01
请参看下面的源代码: <?PHP function format_output($output) {/***************************************************************************** Takes a raw string ($output) and formats it for output using a special* stripped down markup that is similar to HTML****************************************************************************/ $output = htmlspecialchars(stripslashes($output)); /* new paragraph */$output = str_replace('[p]', '<p>', $output); /* bold */$output = str_replace('[b]', '<b>', $output);$output = str_replace('[/b]', '</b>', $output); /* italics */$output = str_replace('[i]', '<i>', $output);$output = str_replace('[/i]', '</i>', $output); /* preformatted */$output = str_replace('[pre]', '<pre>', $output);$output = str_replace('[/pre]', '</pre>', $output); /* indented blocks (blockquote) */$output = str_replace('[indent]', '<blockquote>', $output);$output = str_replace('[/indent]', '</blockquote>', $output); /* anchors */$output = ereg_replace('\[anchor="([[:graph:]]+)"\]', '<a name="\\1"></a>', $output); /* links, note we try to prevent JavaScript in links */$output = str_replace('[link="Javascript', '[link=" javascript', $output);$output = ereg_replace('\[link="([[:graph:]]+)"\]', '<a href="\\1">', $output);$output = str_replace('[/link]', '</a>', $output); return nl2br($output);} ?>一些注意的地方: 记住替换自定义标记生成HTML标记字符串是在调用htmlspecialchars()函数之后,而不是在这个调用之前,否则你的艰苦的工作在调用htmlspecialchars()后将付之东流。 在经过转换之后,查找HTML代码将是替换过的,如双引号"将成为" nl2br()函数将回车换行符转换为<br>标记,也要在htmlspecialchars()之后。 当转换[links=""] 到 <a href="">, 你必须确认提交者不会插入JavaScript脚本,一个简单的方法去更改[link="Javascript 到 [link=" javascript, 这种方式将不替换,只是将原本的代码显示出来。 outputlib.PHP在浏览器中调用test.php,可以看到format_output() 的使用情况 正常的HTML标记不能被使用,用下列的特殊标记替换它: - this is bold- this is italics- this is [link="httpww.phPBuilder.com"]a link[/link]- this is [anchor="test"]an anchor, and a [link="#test"]link[/link] to the anchor [p]段落[pre]预先格式化[/pre][indent]交错文本[/indent] 这些只是很少的标记,当然,你可以根据你的需求随意加入更多的标记 Conclusion结论 这个讨论提供安全显示用户输入的方法,可以使用在下列程序中 留言板用户建议系统公告BBS系统