当前位置: 首页 > 图文教程 > 网络编程 > PHP > PHP中显示格式化的用户输入
FormattingwithCustomMarkupTags
用户自己的标记作格式化
你可以提供特殊的标记给用户使用,例如,你可以允许使用...加重显示,...斜体显示,这样做简单的查找替换操作就可以了:$output=str_replace("[b]","<b>",$output);
$output=str_replace("[i]","<i>",$output);
再作的好一点,我们可以允许用户键入一些链接。例如,用户将允许输入[link="url"]...[/link],我们将转换为<ahref="">...</a>语句
这时,我们不能使用一个简单的查找替换,应该使用正则表达式进行替换:
$output=ereg_replace('\[link="([[:graph:]]+)"\]','<ahref="\\1">',$output);
ereg_replace()的执行就是:
查找出现[link="..."]的字符串,使用<ahref="...">替换它
[[:graph:]]的含义是任何非空字符,有关正则表达式请看相关的文章。
在outputlib.php的format_output()函数提供这些标记的转换,总体上的原则是:
调用htmlspecialchars()将HTML标记转换成特殊编码,将不该显示的HTML标记过滤掉,
然后,将一系列我们自定义的标记转换相应的HTML标记。
请参看下面的源代码:
<?php
functionformat_output($output){
/****************************************************************************
*Takesarawstring($output)andformatsitforoutputusingaspecial
*strippeddownmarkupthatissimilartoHTML
****************************************************************************/
$output=htmlspecialchars(stripslashes($output));
/*newparagraph*/
$output=str_replace('[p]','<p>',$output);
/*bold*/
$output=str_replace('','<b>',$output);
$output=str_replace('','</b>',$output);
/*italics*/
$output=str_replace('','<i>',$output);
$output=str_replace('','</i>',$output);
/*preformatted*/
$output=str_replace('[pre]','<pre>',$output);
$output=str_replace('[/pre]','</pre>',$output);
/*indentedblocks(blockquote)*/
$output=str_replace('[indent]','<blockquote>',$output);
$output=str_replace('[/indent]','</blockquote>',$output);
/*anchors*/
$output=ereg_replace('\[anchor="([[:graph:]]+)"\]','<aname="\\1"></a>',$output);
/*links,notewetrytopreventjavascriptinlinks*/
$output=str_replace('[link="javascript','[link="javascript',$output);
$output=ereg_replace('\[link="([[:graph:]]+)"\]','<ahref="\\1">',$output);
$output=str_replace('[/link]','</a>',$output);
returnnl2br($output);
}
?>
一些注意的地方:
记住替换自定义标记生成HTML标记字符串是在调用htmlspecialchars()函数之后,而不是在这个调用之前,否则你的艰苦的工作在调用htmlspecialchars()后将付之东流。
在经过转换之后,查找HTML代码将是替换过的,如双引号"将成为"
nl2br()函数将回车换行符转换为<br>标记,也要在htmlspecialchars()之后。
当转换[links=""]到<ahref="">,你必须确认提交者不会插入javascript脚本,一个简单的方法去更改[link="javascript到[link="javascript,这种方式将不替换,只是将原本的代码显示出来。
outputlib.php
在浏览器中调用test.php,可以看到format_output()的使用情况
正常的HTML标记不能被使用,用下列的特殊标记替换它:
-thisisbold
-thisisitalics
-thisis[link="http://www.phpbuilder.com"]alink[/link]
-thisis[anchor="test"]ananchor,anda[link="#test"]link[/link]totheanchor
[p]段落
[pre]预先格式化[/pre]
[indent]交错文本[/indent]
这些只是很少的标记,当然,你可以根据你的需求随意加入更多的标记
Conclusion
结论
这个讨论提供安全显示用户输入的方法,可以使用在下列程序中
留言板
用户建议
系统公告
BBS系统
评论 (0) All