關於在php中html標籤的轉換問題的解決,轉義與反轉義
阿新 • • 發佈:2019-01-06
很多朋友在寫php的時候,難免會遇到需要將html標籤進行轉義儲存。比如存入資料庫、xml檔案等。而儲存進去後,讀取出來則需要轉換成html輸出。網上有許多人編寫的轉換函式,很長很難懂。其實php早就自帶有這樣的函式。大可不必自己編寫。
下面分別介紹這兩個函式。
1.htmlentities()函式:
說明:將html標籤轉換成特殊字元。例如將<script>轉換成"<script>"
例子:
- // 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改成單引號。---呼!
上面的語句執行後,將生成下面的結果
- 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標籤。
例子:
- $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