8.3.2 和HTML标签相关的字符串格式化函数
和HTML标签相关联的字符串格式化
函数:nl2br( )
语法:string nl2br ( string string )�将字符串中”\n”转成HTML换行符“<br />”
函数:htmlspecialchars()
语法:string htmlspecialchars ( string string [,
int quote_style [, string charset]] )�把指定特殊符号转换成实体,如<>
'&' :'&' '“':'"'
''' :''' '< ':'<'
'>' :'>'
函数: htmlentities()
语法:string htmlentities ( string string [, int
quote_style [,string charset]])�可以将所有的非ASCII码转换成对应实体代码。
<html>
<body>
<?php
$str = "<B>WebServer:</B> & 'Linux' & 'Apache'"; //常有HTML标记和单引号的字符串
echo htmlspecialchars($str, ENT_COMPAT); //转换HTML标记和转换双引号
echo "<br>\n";
echo htmlspecialchars($str, ENT_QUOTES); //转换HTML标记和转换两种引号
echo "<br>\n";
echo htmlspecialchars($str, ENT_NOQUOTES); //转换HTML标记和不对引号转换
?>
</body>
</html>
函数:string strip_tags()
语法:string strip_tags(string str[,string
allowable_tags])�删除HTML的标签函数
<?php
$str = "<font color='red' size=7>Linux</font> <i>Apache</i> <u>Mysql<u> <b>PHP</b>";
//删除了全部HTML标签,输出:Linux Apache Mysql PHP
echo strip_tags($str);
//输出<font color='red' size=7>Linux</font> Apache Mysql PHP
echo strip_tags($str, "<font>");
//输出Linux <i>Apache</i> <u>Mysql<u> <b>PHP</b>
echo strip_tags($str, "<b><u><i>");
1.php
<?php
if(isset($_POST['dosubmit'])) {
$title = $_POST['title'];
echo stripslashes(addslashes($title))."<br>";
echo htmlspecialchars($title);
}
?>
<br>
<form action="" method="post">
title: <input type="text" name="title" value="" />
<input type="submit" name="dosubmit" value="提交" /><br>
</form>
3.php
<?php
if(isset($_POST['dosubmit'])) {
$title = $_POST['title'];
echo strip_tags($title, "<b><u>");
}
?>
<br>
<form action="" method="post">
title: <input type="text" name="title" value="" />
<input type="submit" name="dosubmit" value="提交" /><br>
</form>
test.php
<?php
$str = "this is a test\n";
$str .="this is a demo\n";
$str .="this is a hello\n";
echo nl2br($str);