標籤:
很多朋友在寫php的時候,難免會遇到需要將html標籤進行轉義儲存。比如存入資料庫、xml檔案等。而儲存進去後,讀取出來則需要轉換成html輸出。網上有許多人編寫的轉換函式,很長很難懂。其實php早就內建有這樣的函數。大可不必自己編寫。
下面分別介紹這兩個函數。
1.htmlentities()函數:
說明:將html標籤轉換成特殊字元。例如將<script>轉換成"<script>"
例子:
[PHP] view plaincopy
- // An imaginary article submission from a bad user
- // it will redirect anyone to example.com if the code is run in a browser
- $userInput = "I am going to hax0r your site, hahaha!
- <script type='text/javascript'>
- window.location = 'http://www.example.com/'
- </script>'";
-
- //Lets make it safer before we use it
- $userInputEntities = htmlentities($userInput);
-
- //Now we can display it
- echo $userInputEntities;
由於最近csdn的控制項比較垃圾,請將上面的$apos改成單引號。---呼!
上面的語句執行後,將產生下面的結果
[HTML] view plaincopy
- I am going to hax0r your site, hahaha!
- <script type='text/javascript'>
- window.location = 'http://www.88web.org/'
- </script>'
2.html_entity_decode()函數
說明:將htmlentities()函數轉義過的字串轉成html標籤。
例子:
[PHP] view plaincopy
- $orig = "I'll /"walk/" the <b>dog</b> now";
-
- $a = htmlentities($orig);
-
- $b = html_entity_decode($a);
-
- echo $a; // I will "walk" the <b>dog</b> now
-
- echo $b; // I will "walk" the <b>dog</b> now
轉載自:http://blog.sina.com.cn/s/blog_a144530d0101d6li.html
關於在php中html標籤的轉換問題的解決