html_entity_decode 和 htmlspecialchars_decode 都是 PHP 中用于解码 HTML 实体的函数,但它们的作用范围有所不同:

html_entity_decode

用于将所有的 HTML 实体转换回其对应的字符,包括一些更复杂的 HTML 实体。例如:

  • & 转换为 &
  • &lt; 转换为 <
  • &gt; 转换为 >
  • &quot; 转换为 “
  • &apos; 转换为 ‘
  • 还包括更多其他的 HTML 实体,如 &copy; 转换为 ©

语法:

html_entity_decode(string $string, int $flags = ENT_QUOTES | ENT_HTML401, string $encoding = ‘UTF-8’): string

示例:

<?php
$encoded = “Hello &amp; welcome to &lt;my site&gt; &copy; 2024”;
$decoded = html_entity_decode($encoded);
echo $decoded; // 输出:Hello & welcome to <my site> © 2024

htmlspecialchars_decode

函数用于将特定的几个 HTML 实体转换回其对应的字符,主要包括:

  • &amp; 转换为 &
  • &lt; 转换为 <
  • &gt; 转换为 >
  • &quot; 转换为 “
  • &#039; 或 &apos; 转换为 ‘(取决于 flags 参数)

语法:

htmlspecialchars_decode(string $string, int $flags = ENT_COMPAT | ENT_HTML401): string

示例:

<?php
$encoded = “Hello &amp; welcome to &lt;my site&gt;”;
$decoded = htmlspecialchars_decode($encoded);
echo $decoded; // 输出:Hello & welcome to <my site>

区别

  • html_entity_decode 适用于需要解码所有 HTML 实体的场景,包括一些特殊的和较少见的实体。
  • htmlspecialchars_decode 仅适用于解码那些由 htmlspecialchars 编码的实体(即:&amp;, &lt;, &gt;, &quot;, &#039;)。
    使用场景

使用

  • 当你从富文本编辑器(如 UEditor)保存的内容中读取数据时,因为这些编辑器可能会包含多种 HTML 实体,因此适合使用 html_entity_decode 来解码所有可能的实体。
  • 当你处理的数据是由 htmlspecialchars 转码的,主要是一些基本的安全性处理(如防止 XSS 攻击)时,可以使用 htmlspecialchars_decode。

作者 admin

百度广告效果展示