很多朋友在写php的时候,难免会遇到需要将html标签进行转义存储。比如存入数据库、xml文件等。而存储进去后,读取出来则需要转换成html输出。我也是找了两天,才找到解决方法的。
下面分别介绍这两个函数。
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./'
-
</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
|