關於在php中html標籤的轉換問題的解決

來源:互聯網
上載者:User

標籤:

很多朋友在寫php的時候,難免會遇到需要將html標籤進行轉義儲存。比如存入資料庫、xml檔案等。而儲存進去後,讀取出來則需要轉換成html輸出。網上有許多人編寫的轉換函式,很長很難懂。其實php早就內建有這樣的函數。大可不必自己編寫。

下面分別介紹這兩個函數。

1.htmlentities()函數:

說明:將html標籤轉換成特殊字元。例如將<script>轉換成"&lt;script&gt;"

例子:

[PHP] view plaincopy
  1. // An imaginary article submission from a bad user  
  2. //  it will redirect anyone to example.com if the code is run in a browser  
  3. $userInput = "I am going to hax0r your site, hahaha!  
  4.     <script type=&apos;text/javascript&apos;>  
  5.     window.location = &apos;http://www.example.com/&apos;  
  6.     </script>&apos;";  
  7.       
  8. //Lets make it safer before we use it  
  9. $userInputEntities = htmlentities($userInput);  
  10.   
  11. //Now we can display it  
  12. echo $userInputEntities;  

由於最近csdn的控制項比較垃圾,請將上面的$apos改成單引號。---呼!

上面的語句執行後,將產生下面的結果

[HTML] view plaincopy
  1. I am going to hax0r your site, hahaha!  
  2.     <script type=&apos;text/javascript&apos;>  
  3.     window.location = &apos;http://www.88web.org/&apos;  
  4.     </script>&apos;  
2.html_entity_decode()函數

說明:將htmlentities()函數轉義過的字串轉成html標籤。

例子:

[PHP] view plaincopy
  1. $orig = "I&apos;ll /"walk/" the <b>dog</b> now";  
  2.   
  3. $a = htmlentities($orig);  
  4.   
  5. $b = html_entity_decode($a);  
  6.   
  7. echo $a; // I will "walk" the <b>dog</b> now  
  8.   
  9. echo $b; // I will "walk" the <b>dog</b> now  

 

轉載自:http://blog.sina.com.cn/s/blog_a144530d0101d6li.html

關於在php中html標籤的轉換問題的解決

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.