转化方法:1、用html_entity_decode()函数,可以把html实体转为字符;2、用htmlspecialchars_decode()函数,可以把一些预定义的html实体(“<”、“>”、“&”等)转为字符。
本教程操作环境:windows7系统、php7.1版、dell g3电脑
php把html实体转化为字符
1、使用html_entity_decode()函数
html_entity_decode() 函数把 html 实体转换为字符。
html_entity_decode() 函数是 htmlentities() 函数的反函数。
语法:
html_entity_decode(string,flags,character-set)
参数描述
string 必需。规定要解码的字符串。
flags 可选。规定如何处理引号以及使用哪种文档类型。可用的引号类型:
ent_compat - 默认。仅解码双引号。ent_quotes - 解码双引号和单引号。ent_noquotes - 不解码任何引号。规定使用的文档类型的附加 flags:
ent_html401 - 默认。作为 html 4.01 处理代码。ent_html5 - 作为 html 5 处理代码。ent_xml1 - 作为 xml 1 处理代码。ent_xhtml - 作为 xhtml 处理代码。
character-set 可选。一个规定了要使用的字符集的字符串。允许的值:
utf-8 - 默认。ascii 兼容多字节的 8 位 unicodeiso-8859-1 - 西欧iso-8859-15 - 西欧(加入欧元符号 + iso-8859-1 中丢失的法语和芬兰语字母)cp866 - dos 专用 cyrillic 字符集cp1251 - windows 专用 cyrillic 字符集cp1252 - windows 专用西欧字符集koi8-r - 俄语big5 - 繁体中文,主要在台湾使用gb2312 - 简体中文,国家标准字符集big5-hkscs - 带香港扩展的 big5shift_jis - 日语euc-jp - 日语macroman - mac 操作系统使用的字符集注释:在 php 5.4 之前的版本,无法被识别的字符集将被忽略并由 iso-8859-1 替代。自 php 5.4 起,无法被识别的字符集将被忽略并由 utf-8 替代。
示例1:把一些 html 实体转换为字符:
<?phpheader('content-type:text/html;charset=utf-8'); $str = "jane & 'tarzan'";echo html_entity_decode($str, ent_compat); // will only convert double quotesecho "<br>";echo html_entity_decode($str, ent_quotes); // converts double and single quotesecho "<br>";echo html_entity_decode($str, ent_noquotes); // does not convert any quotes?>
示例2:通过使用西欧字符集,把一些 html 实体转换为字符:
<?php$str = "my name is øyvind åsane. i'm norwegian.";echo html_entity_decode($str, ent_quotes, "iso-8859-1");?>
2、使用htmlspecialchars_decode() 函数
htmlspecialchars_decode() 函数把一些预定义的 html 实体转换为字符。
会被解码的 html 实体是:
& 解码成 & (和号)
" 解码成 " (双引号)
' 解码成 ' (单引号)
< 解码成 < (小于)
> 解码成 > (大于)
htmlspecialchars_decode() 函数是 htmlspecialchars() 函数的反函数。【相关文章推荐:《php怎么将字符转为实体》】
语法:
htmlspecialchars_decode(string,flags)
参数描述
string 必需。规定要解码的字符串。
flags 可选。规定如何处理引号以及使用哪种文档类型。可用的引号类型:
ent_compat - 默认。仅解码双引号。ent_quotes - 解码双引号和单引号。ent_noquotes - 不解码任何引号。规定使用的文档类型的附加 flags:
ent_html401 - 默认。作为 html 4.01 处理代码。ent_html5 - 作为 html 5 处理代码。ent_xml1 - 作为 xml 1 处理代码。ent_xhtml - 作为 xhtml 处理代码。
示例:把一些预定义的 html 实体转换为字符:
<?php$str = "jane & 'tarzan'";echo htmlspecialchars_decode($str, ent_compat); // 默认,仅解码双引号echo "<br>";echo htmlspecialchars_decode($str, ent_quotes); // 解码双引号和单引号echo "<br>";echo htmlspecialchars_decode($str, ent_noquotes); // 不解码任何引号?>
推荐学习:《php视频教程》
以上就是php怎么把html实体转化为字符的详细内容。