欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

php htmlentities()函数的定义和用法

程序员文章站 2023-12-21 17:51:34
php htmlentities() 函数把字符转换为 html 实体,本文章向码农介绍php htmlentities() 函数基本使用方法和实例介绍,需要的码农可以参考...

php htmlentities() 函数把字符转换为 html 实体,本文章向码农介绍php htmlentities() 函数基本使用方法和实例介绍,需要的码农可以参考一下。

定义和用法

htmlentities() 函数把字符转换为 html 实体。

提示:要把 html 实体转换回字符,请使用 html_entity_decode() 函数。

提示:请使用 get_html_translation_table() 函数来返回 htmlentities() 使用的翻译表。

语法

htmlentities(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 = "bill & 'steve'"; 
echo htmlentities($str, ent_compat); // 只转换双引号 
echo "<br>"; 
echo htmlentities($str, ent_quotes); // 转换双引号和单引号 
echo "<br>"; 
echo htmlentities($str, ent_noquotes); // 不转换任何引号 
?> 

以上代码的 html 输出如下(查看源代码):

<!doctype html> 
<html> 
<body> 
bill & 'steve'<br> 
bill & 'tarzan'<br> 
bill & 'steve'
</body> 
</html> 

以上代码的浏览器输出:

bill & 'steve'
bill & 'steve'
bill & 'steve' 

例子 2

通过使用西欧字符集,把一些字符转换为 html 实体:

<?php 
$str = "my name is ?yvind ?sane. i'm norwegian."; 
echo htmlentities($str, ent_quotes, "iso-8859-1"); 
// will only convert double quotes (not single quotes), and uses the character-set western european 
?> 

以上代码的 html 输出如下(查看源代码):

<!doctype html> 
<html> 
<body> 
my name is øyvind åsane. i'm norwegian. 
</body> 
</html> 

以上代码的浏览器输出:

my name is ?yvind ?sane. i'm norwegian.

以上这篇php htmlentities()函数的定义和用法就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持。

上一篇:

下一篇: