转义方法:1、用htmlspecialchars_decode()函数,可将5个预定义的html实体转为字符,语法“htmlspecialchars_decode(string,flags)”;2、用html_entity_decode()函数,可将指定html实体转为字符,语法“html_entity_decode(string,flags,character-set)”。
本教程操作环境:windows7系统、php8版、dell g3电脑
php提供了 两个函数来将html实体转义为字符
htmlspecialchars_decode()函数
html_entity_decode()函数
下面就来了解一下这两个函数。
方法1:使用htmlspecialchars_decode()函数将html实体转义为字符
htmlspecialchars_decode() 函数把一些预定义的 html 实体转换为字符。
会被解码的 html 实体是:
& 解码成 & (和号)
" 解码成 (双引号)
' 解码成 ' (单引号)
< 解码成 83f65bc4a1db2fdeb5b81acab0995c6d (大于)
语法:
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 = "this is some <b>bold</b> text.";echo htmlspecialchars_decode($str);?>
htmlspecialchars_decode() 函数只能转义5种html 实体,那么其他html 实体想要转义要怎么处理?可以使用html_entity_decode()函数。
方法2:使用html_entity_decode()函数将html实体转义为字符
html_entity_decode() 函数把 html 实体转换为字符。
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 替代。
示例:
<?php$str = "<© w3csçh°°¦§>";echo html_entity_decode($str);?>
输出:
<© w3csçh°°¦§>
推荐学习:《php视频教程》
以上就是php怎么将html实体转义为字符的详细内容。