实例
把预定义的字符 c07b7fc73b688c4822109e008aa2ee3d (大于)转换为 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() 函数把一些预定义的字符转换为 html 实体。
预定义的字符是:
& (和号)成为 &
" (双引号)成为 "
' (单引号)成为 '
< (小于)成为 <
> (大于)成为 >
提示:要把特殊的 html 实体转换回字符,请使用 htmlspecialchars_decode() 函数。
语法
htmlspecialchars(string,flags,character-set,double_encode)
参数 描述
string 必需。规定要转换的字符串。
flags 可选。规定如何处理引号、无效的编码以及使用哪种文档类型。可用的引号类型:
ent_compat - 默认。仅编码双引号。
ent_quotes - 编码双引号和单引号。
ent_noquotes - 不编码任何引号。
无效的编码:
ent_ignore - 忽略无效的编码,而不是让函数返回一个空的字符串。应尽量避免,因为这可能对安全性有影响。
ent_substitute - 把无效的编码替代成一个指定的带有 unicode 替代字符 u+fffd(utf-8)或者 &#fffd; 的字符,而不是返回一个空的字符串。
ent_disallowed - 把指定文档类型中的无效代码点替代成 unicode 替代字符 u+fffd(utf-8)或者 &#fffd;。
规定使用的文档类型的附加 flags:
ent_html401 - 默认。作为 html 4.01 处理代码。
ent_html5 - 作为 html 5 处理代码。
ent_xml1 - 作为 xml 1 处理代码。
ent_xhtml - 作为 xhtml 处理代码。
character-set 可选。一个规定了要使用的字符集的字符串。允许的值:
utf-8 - 默认。ascii 兼容多字节的 8 位 unicode
iso-8859-1 - 西欧
iso-8859-15 - 西欧(加入欧元符号 + iso-8859-1 中丢失的法语和芬兰语字母)
cp866 - dos 专用 cyrillic 字符集
cp1251 - windows 专用 cyrillic 字符集
cp1252 - windows 专用西欧字符集
koi8-r - 俄语
big5 - 繁体中文,主要在台湾使用
gb2312 - 简体中文,国家标准字符集
big5-hkscs - 带香港扩展的 big5
shift_jis - 日语
euc-jp - 日语
macroman - mac 操作系统使用的字符集
注释:在 php 5.4 之前的版本,无法被识别的字符集将被忽略并由 iso-8859-1 替代。自 php 5.4 起,无法被识别的字符集将被忽略并由 utf-8 替代。
double_encode 可选。一个规定了是否编码已存在的 html 实体的布尔值。true - 默认。将对每个实体进行转换。
false - 不会对已存在的 html 实体进行编码。
技术细节
返回值: 返回已转换的字符串。
如果 string 包含无效的编码,则返回一个空的字符串,除非设置了 ent_ignore 或者 ent_substitute 标志。
php 版本: 4+
更新日志: 在 php 5 中,character-set 参数的默认值改为 utf-8。
在 php 5.4 中,新增了:ent_substitute、ent_disallowed、ent_html401、ent_html5、ent_xml1 和 ent_xhtml。
在 php 5.3 中,新增了 ent_ignore。
在 php 5.2.3 中,新增了 double_encode 参数。
在 php 4.1 中,新增了 character-set 参数。
更多实例
实例 1
把一些预定义的字符转换为 html 实体:
<?php
$str = "jane & 'tarzan'";
echo htmlspecialchars($str, ent_compat); // 默认,仅编码双引号
echo "<br>";echo htmlspecialchars($str, ent_quotes); // 编码双引号和单引号
echo "<br>";echo htmlspecialchars($str, ent_noquotes); // 不编码任何引号
?>
上面代码的 html 输出如下(查看源代码):
<!doctype html>
<html>
<body>
jane & 'tarzan'<br>jane & 'tarzan'<br>jane & 'tarzan'
</body>
</html>
上面代码的浏览器输出如下:
jane & 'tarzan'
jane & 'tarzan'
jane & 'tarzan'
实例 2
把双引号转换为 html 实体:
<?php
$str = 'i love "php".';
echo htmlspecialchars($str, ent_quotes); // 编码双引号和单引号
?>;
上面代码的 html 输出如下(查看源代码):
<!doctype html>
<html>
<body>
i love "php".
</body>
</html>
上面代码的浏览器输出如下:
i love "php".
htmlspecialchars_decode() 函数把一些预定义的 html 实体转换为字符。
<?php
$str = "this is some <b>bold</b> text.";
echo htmlspecialchars_decode($str);
?>
会被解析成
<!doctype html>
<html>
<body>
this is some <b>bold</b> text.
</body>
</html>
用户商品详情的输出。
<p>
{sh:$info.intro|htmlspecialchars_decode}
</p>
以上就是php把预定义的字符转换为html实体函数htmlspecialchars()的详细内容。