Home  >  Article  >  Backend Development  >  How to solve php html tag conversion problem

How to solve php html tag conversion problem

藏色散人
藏色散人Original
2020-08-13 09:29:393778browse

php html标签转换问题的解决办法:1、使用“htmlentities()”函数将html标签转换成特殊字符;2、使用“html_entity_decode()”函数将htmlentities函数转义过的字符串转成html标签。

How to solve php html tag conversion problem

推荐:《PHP视频教程

 很多朋友在写php的时候,难免会遇到需要将html标签进行转义存储。比如存入数据库、xml文件等。而存储进去后,读取出来则需要转换成html输出。网上有许多人编写的转换函数,很长很难懂。其实php早就自带有这样的函数。大可不必自己编写。

下面分别介绍这两个函数。

1.htmlentities()函数:

说明:将html标签转换成特殊字符。例如将<script>转换成"&lt;script&gt;"</p> <p>例子:</p> <p><strong>[PHP]</strong> view plaincopy</p> <ol style="margin-left:45px;"> <li><span style="color:#000000;"><span style="color:#008200;">// An imaginary article submission from a bad user</span>  </span></li> <li> </li> <li><span style="color:#000000;"><span style="color:#008200;">//  it will redirect anyone to example.com if the code is run in a browser</span>  </span></li> <li> </li> <li><span style="color:#000000;"><span style="color:#dd0000;">$userInput</span> = "I am going to hax0r your site, hahaha!  </span></li> <li> </li> <li><span style="color:#000000;">    <script type=&apos;text/javascript&apos;>  </span></li> <li> </li> <li><span style="color:#000000;">    window.location = &apos;http:<span style="color:#008200;">//www.example.com/&apos;</span>  </span></li> <li> </li> <li><span style="color:#000000;">    </script>'";  

  •       
  • //Lets make it safer before we use it  
  • $userInputEntities = htmlentities($userInput);  
  •   
  • //Now we can display it  
  • echo $userInputEntities;  
  • 由于最近csdn的控件比较垃圾,请将上面的$apos改成单引号。---呼!

    上面的语句执行后,将生成下面的结果

    [HTML] view plaincopy

    1. I am going to hax0r your site, hahaha!  
    2.     <script type='text/javascript'>  
    3.     window.location = 'http://www.88web.org/'  
    4.     script>'  

    2.html_entity_decode()函数

    说明:将htmlentities()函数转义过的字符串转成html标签。

    例子:

    [PHP] view plaincopy

    1. $orig = "I'll /"walk/" the dog now";  
    2.   
    3. $a = htmlentities($orig);  
    4.   
    5. $b = html_entity_decode($a);  
    6.   
    7. echo $a// I will "walk" the dog now  
    8.   
    9. echo $b// I will "walk" the dog now  
    10.  

    转载自页面     http://www.cankaojishu.com/bcyy/82144.html

    The above is the detailed content of How to solve php html tag conversion problem. For more information, please follow other related articles on the PHP Chinese website!

    Statement:
    The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn