天天看點

htmlentities、addslashes 、htmlspecialchars的使用

1、html_entity_decode():把html實體轉換為字元。

Eg:$str = "just atest & 'learn to use '";

echo html_entity_decode($str);

echo "<br />";

echo html_entity_decode($str,ENT_QUOTES);

echo html_entity_decode($str,ENT_NOQUOTES);

輸出如下:

just a test & 'learn to use '

2、htmlentities():把字元轉換為html實體。

Eg:$str = "just a test  & 'learn to use'";

echo  htmlentities($str,ENT_COMPAT);

echo  "<br/>";

echo  htmlentities($str, ENT_QUOTES);

echo  htmlentities($str, ENT_NOQUOTES);

just a test & 'learn to use'

檢視源代碼如下:

just a test  &amp;  'learn to use'<br />

just a test  &amp;  &#039;learn to use&#039;<br />

just a test  &amp;  'learn to use'

3、addslashes():在指定的預定義字元前添加反斜杠

預定義字元包括:單引号(‘),雙引号(“),反斜杠(\),NULL

預設情況下,PHP指令 magic_quotes_gpc 為

on,對所有的GET、POST 和COOKIE 資料自動運作 addslashes()。不要對已經被 magic_quotes_gpc

轉義過的字元串使用 addslashes(),因為這樣會導緻雙層轉義。遇到這種情況時可以使用函數get_magic_quotes_gpc()

進行檢測。

Eg:$str3="\  just  a   '   \" test";

echoaddslashes($str3);

輸出:

\\ just a \' \" test

4、stripslashes():删除由addslashes函數添加的反斜杠

Eg:$str4="\\ just a \'\" test";

echo  stripslashes($str4);        

just a ' " test

5、 htmlspecialchars():把一些預定義的字元轉換為html實體。

預定義字元包括:

& (和号) 成為&amp;  

 " (雙引号) 成為&quot;

' (單引号) 成為&#039;

< (小于) 成為&lt;

> (大于) 成為&gt;

Eg:$str5 = "just atest  & 'learn to use'";

echo htmlspecialchars($str5, ENT_COMPAT);

echo  htmlspecialchars($str5, ENT_QUOTES);

echo  htmlspecialchars($str5, ENT_NOQUOTES);

檢視源代碼:  just a test  &amp; 'learn to use'<br />

                     just a test  &amp; &#039;learn to use&#039;<br />

                     just a test  &amp; 'learn to use'

6、 htmlspecialchars_decode():把一些預定義的html實體轉換為字元。

會被解碼的html實體包括:&amp; 成為 &(和号)

 &quot; 成為 " (雙引号)

 &#039; 成為 ' (單引号)

 &lt; 成為 < (小于)

 &gt; 成為 > (大于)