Home  >  Article  >  Backend Development  >  What is the function that php uses to convert html code into entities?

What is the function that php uses to convert html code into entities?

青灯夜游
青灯夜游Original
2022-02-10 17:27:072205browse

php把html代码转换成实体的函数是htmlspecialchars(),该函数可以把预定义的字符转换为HTML实体,语法“htmlspecialchars(string,flags,character,double_encode)”。

What is the function that php uses to convert html code into entities?

本教程操作环境:windows7系统、PHP7.1版、DELL G3电脑

php把html代码转换成实体的函数是htmlspecialchars()。

示例:

<?php
$str = "This is some <b>bold</b> text.";
echo htmlspecialchars($str);
?>

What is the function that php uses to convert html code into entities?

说明:

htmlspecialchars()函数是使用来把一些预定义的字符转换为HTML实体,返回转换后的新字符串,原字符串不变。如果 string 包含无效的编码,则返回一个空的字符串,除非设置了 ENT_IGNORE 或者 ENT_SUBSTITUTE 标志;

被转换的预定义的字符有:

  • &:转换为&

  • ":转换为"

  • ':转换为成为 '

htmlspecialchars()函数有四个参数,第一个参数规定了需要转换的字符串;第二个参数规定了如何处理引号、无效的编码以及使用哪种文档类型,是可选参数;第三个参数也是可选参数,规定了要使用的字符集的字符串;第四个参数也是可选参数,规定了是否编码已存在的 HTML 实体的布尔值(TRUE:将对每个实体进行转换;FALSE:不会对已存在的HTML实体进行编码);

htmlspecialchars()函数语法格式:

$str = htmlspecialchars(string,flags,character,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

可选。一个规定了要使用的字符集的字符串。

允许的值:

  • 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视频教程

The above is the detailed content of What is the function that php uses to convert html code into entities?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn