8.3.2 和HTML標簽相關的字符串格式化函數(shù)
和HTML標簽相關聯(lián)的字符串格式化
函數(shù):nl2br( )
語法:string nl2br ( string string )?將字符串中”\n”轉成HTML換行符“<br />”
函數(shù):htmlspecialchars()
語法:string htmlspecialchars ( string string [,
int quote_style [, string charset]] )?把指定特殊符號轉換成實體,如<>
'&' :'&' '“':'"'
''' :''' '< ':'<'
'>' :'>'
函數(shù): 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>
函數(shù):string strip_tags()
語法:string strip_tags(string str[,string
allowable_tags])?刪除HTML的標簽函數(shù)
<?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);