PHP 格式转换类——封装字符串转换方法,UseFun格式转换类中封装了一些字符串的转换方法,其根本就是对HTML格式的字符串进行转义。使其在输出时不被当做HTML代码被执行。
PHP 格式转换类 语法
/******************************************************************
* @ 说明:格式转换类
******************************************************************/
class UseFun{
function UnHtml(text){content=(nl2br(htmlspecialchars(text)));content=str_replace("[strong]","<strong>",content);content=str_replace("[/strong]","</strong>",content);
content=str_replace("[em]","<em>",content);
content=str_replace("[/em]","</em>",content);
content=str_replace("[u]","<u>",content);
content=str_replace("[/u]","</u>",content);
content=str_replace("[font color=#FF0000]","<font color=#FF0000>",content);
content=str_replace("[font color=#00FF00]","<font color=#00FF00>",content);
content=str_replace("[font color=#0000FF]","<font color=#0000FF>",content);
content=str_replace("[font face=楷体_GB2312]","<font face=楷体_GB2312>",content);
content=str_replace("[font face=宋体]","<font face=新宋体>",content);
content=str_replace("[font face=隶书]","<font face=隶书>",content);
content=str_replace("[/font]","</font>",content);
content=str_replace("[font size=1]","<font size=1>",content);
content=str_replace("[font size=2]","<font size=2>",content);
content=str_replace("[font size=3]","<font size=3>",content);
content=str_replace("[font size=4]","<font size=4>",content);
content=str_replace("[font size=5]","<font size=5>",content);
content=str_replace("[font size=6]","<font size=6>",content);
content=str_replace("[FIELDSET][LEGEND]","<FIELDSET><LEGEND>",content);
content=str_replace("[/LEGEND]","</LEGEND>",content);
content=str_replace("[/FIELDSET]","</FIELDSET>",content);
return $content;
}
}
PHP 格式转换类 示例
在本示例中编写一个简单的留言本功能,通过格式转换类对留言本中输出的内容进行转义,确保HTML标记以代码形式输出。
其关键代码如下:
<table width="754" border="0" align="center" cellpadding="0" cellspacing="1">
<?php
include("conn/conn.php"); //载入数据库连接文件
include("function.php"); //载入类文件
unhtml=new UseFun(); //实例化格式转换类sql=mysql_query("select * from tb_guestbook order by createtime desc");
//执行查询语句
info=mysql_fetch_array(sql); //获取查询结果集
if(info==false){
echo "暂无留言";
}else{
do{
?>
<tr>
<td width="151" height="25" bgcolor="#FFFFFF"><div align="center">主
题:</div></td>
<td width="600" bgcolor="#FFFFFF"> <?php echounhtml->UnHtml(info
['title']);?></td>
</tr>
<tr>
<td height="95" bgcolor="#FFFFFF"><div align="center">内
容:</div></td>
<td bgcolor="#FFFFFF"> <?php echounhtml->UnHtml(info['content']);?></td>
</tr>
<?php
}
while(info=mysql_fetch_array($sql));
}
?>
</table>