htmlspecialchars()
定义和用法
htmlspecialchars() 函数把一些预定义的字符转换为 HTML 实体。
预定义的字符是:
- & (和号)成为 &
- " (双引号)成为 "
- ' (单引号)成为 '
- < (小于)成为 <
- > (大于)成为 >
实例
把预定义的字符 "<" (小于)和 ">" (大于)转换为 HTML 实体:
<?php
$str = "This is some <b>bold</b> text.";
echo htmlspecialchars($str);
?>上面代码的 HTML 输出如下(查看源代码):
<!DOCTYPE html>
<html>
<body>
This is some <b>bold</b> text.
</body>
</html>上面代码的浏览器输出如下:
This is some <b>bold</b> text.
htmlspecialchars_decode()
定义和用法
实例
把预定义的 HTML 实体 "<"(小于)和 ">"(大于)转换为字符:
<?php
$str = "This is some <b>bold</b> text.";
echo htmlspecialchars_decode($str);
?>上面代码的 HTML 输出如下(查看源代码):
<!DOCTYPE html>
<html>
<body>
This is some <b>bold</b> text.
</body>
</html> 上面代码的浏览器输出如下:
This is some bold text.
本文介绍了PHP中htmlspecialchars函数的使用方法,该函数用于将预定义的特殊字符转换为HTML实体,以防止HTML注入攻击。同时,也讲解了如何利用htmlspecialchars_decode函数将HTML实体还原成原始的字符。
1683

被折叠的 条评论
为什么被折叠?



