get_html_translation_table
get_html_translation_table(int $table = HTML_SPECIALCHARS, int $flags = ENT_QUOTES|ENT_SUBSTITUTE|ENT_HTML401, string $encoding = "UTF-8"): array
返回 htmlspecialchars/htmlentities 内部使用的转换表(字符→实体);HTML_SPECIALCHARS 五个标记字符、HTML_ENTITIES 全量实体(HTML5 下约 1500 项);8.1 起默认 flags 含 ENT_QUOTES。
C C23
#include <stdio.h>
#include <string.h>
/* C 标准库没有 HTML 实体:手写五个特殊字符 */
static void html_escape(const char *s, char *out) {
size_t o = 0;
for (; *s; s++) {
const char *rep = *s == '&' ? "&" : *s == '<' ? "<"
: *s == '>' ? ">" : *s == '"' ? """
: *s == '\'' ? "'" : NULL;
if (rep) { size_t l = strlen(rep); memcpy(out + o, rep, l); o += l; }
else out[o++] = *s;
}
out[o] = '\0';
}
int main(void) {
char buf[64] = {0}; /* 零初始化输出缓冲 */
printf("& -> &\n");
html_escape("<a&>", buf);
printf("escape=%s\n", buf);
return 0;
}
& -> & escape=<a&>
C++ C++26
#include <iostream>
#include <string>
// C++ 标准库没有 HTML 实体表:手写五个特殊字符
static std::string html_escape(const std::string &s) {
std::string out;
out.reserve(s.size());
for (char ch : s) {
switch (ch) {
case '&': out += "&"; break;
case '<': out += "<"; break;
case '>': out += ">"; break;
case '"': out += """; break;
case '\'': out += "'"; break;
default: out += ch;
}
}
return out;
}
int main() {
std::cout << "escape=" << html_escape("<a&>") << '\n';
std::cout << "one & grows to 5=" << (html_escape("&").size() == 5) << '\n';
return 0;
}
escape=<a&> one & grows to 5=1
C# v11.0.100
using System;
using System.Collections.Generic;
using System.Net;
var table = new Dictionary<char, string>
{
['&'] = "&",
['<'] = "<",
['>'] = ">",
};
// 没有公开的转换表 API:手写 htmlspecialchars 风格的五个字符
Console.WriteLine($"& -> {table['&']}, < -> {table['<']}, > -> {table['>']}");
Console.WriteLine($"HtmlEncode={WebUtility.HtmlEncode("<a&>")}");
& -> &, < -> <, > -> > HtmlEncode=<a&>
Go v1.27.4
package main
import (
"fmt"
"html"
)
func main() {
// html.EscapeString 转义五个特殊字符;标准库不暴露可编辑的表
fmt.Println("EscapeString=", html.EscapeString("<a&>"))
fmt.Println("quot=", html.EscapeString("\""), "; apos=", html.EscapeString("'"))
}
EscapeString= <a&> quot= " ; apos= '
Java v27.0.1
import java.util.Map;
public class Main {
// JDK 没有公开的 HTML 转换表:手写五个特殊字符
static final Map<Character, String> TABLE = Map.of(
'&', "&", '<', "<", '>', ">", '"', """, '\'', "'");
static String escape(String s) {
StringBuilder sb = new StringBuilder();
for (char c : s.toCharArray()) sb.append(TABLE.getOrDefault(c, String.valueOf(c)));
return sb.toString();
}
public static void main(String[] args) {
System.out.println("& -> " + TABLE.get('&'));
System.out.println("escape=" + escape("<a&>"));
}
}
& -> & escape=<a&>
JavaScript v26.13.1
// 没有转换表 API:replace 里的映射对象就是那张表
function htmlEscape(s) {
return s.replace(/[&<>"']/g, (c) => ({ "&": "&", "<": "<", ">": ">", '"': """, "'": "'" })[c]);
}
console.log("escape=", htmlEscape("<a&>"));
console.log("quot=", htmlEscape('"'), "; apos=", htmlEscape("'"));
escape= <a&> quot= " ; apos= '
PHP v8.6.0
// htmlspecialchars 背后的那张表:键是字符、值是实体;
// HTML_SPECIALCHARS 收五个标记字符(8.1 起默认 ENT_QUOTES
// 把单引号也收进来)。
$table = get_html_translation_table(HTML_SPECIALCHARS);
echo 'count=', count($table), '; ', $table['&'], ',', $table['<'], ',', $table['"'], "\n";
count=5; &,<,"
Python v3.15.2
# html.entities.html5 把实体名映射到字符(注意:PHP 的表方向相反)
import html
import html.entities
entities = html.entities.html5
print("amp->", entities["amp"], "; lt->", entities["lt"], "; gt->", entities["gt"])
print("escape via html.escape=", html.escape('<script>'))
amp-> & ; lt-> < ; gt-> > escape via html.escape= <script>
Rust v1.99.1
// 标准库没有 HTML 实体表:手写 htmlspecialchars 风格的五个字符
fn html_escape(s: &str) -> String {
let mut out = String::new();
for c in s.chars() {
match c {
'&' => out.push_str("&"),
'<' => out.push_str("<"),
'>' => out.push_str(">"),
'"' => out.push_str("""),
'\'' => out.push_str("'"),
_ => out.push(c),
}
}
out
}
fn main() {
let table = [('&', "&"), ('<', "<"), ('>', ">")];
for (ch, entity) in table {
println!("{ch} -> {entity}");
}
println!("escape={}", html_escape("<a&>"));
}
& -> & < -> < > -> > escape=<a&>
TypeScript v26.13.1
// 没有转换表 API:replace 里的映射对象就是那张表
function htmlEscape(s: string): string {
return s.replace(/[&<>"']/g, (c) => ({ "&": "&", "<": "<", ">": ">", '"': """, "'": "'" })[c] as string);
}
console.log("escape=", htmlEscape("<a&>"));
console.log("quot=", htmlEscape('"'), "; apos=", htmlEscape("'"));
escape= <a&> quot= " ; apos= '
语言差异说明
PHP:get_html_translation_table 把 htmlspecialchars/htmlentities 的内部映射暴露成数组(键=字符、值=实体):HTML_SPECIALCHARS 是防 XSS 的五个标记字符(&、"、'、<、>,8.1 起默认 flags 含 ENT_QUOTES 所以单引号在表里),HTML_ENTITIES 在 ENT_HTML5 下约 1500 项(
、! 这类具名实体全量);flags 同 htmlspecialchars(ENT_QUOTES/ENT_NOQUOTES 控引号、ENT_HTML401/ENT_XHTML/ENT_HTML5 控方言、ENT_SUBSTITUTE 控坏字节替换),encoding 控字符集(UTF-8 默认);注意一个字符可由多种实体表示(" 可写成 "/"/"),表只给 htmlspecialchars 实际使用的那一种;经典用途:array_flip 得到解码表(html_entity_decode 之外的手动路径)、审计转义逻辑、导出表给前端;手册用户注:循环里反复调用很慢(应提出循环外)——与 htmlspecialchars(见该条目)联动:应用层转义用它,自省/自定义映射用本表。
C:标准库没有任何 HTML 实体——示例手写五字符转义(零初始化输出缓冲);没有具名实体的概念。
C++:同样手写 switch 版转义;out.reserve 预留容量;标准库至今不涉及 HTML。
C#:没有公开转换表 API——WebUtility.HtmlEncode(示例)是应用层转义入口(转义五个字符);自定义表用 Dictionary 手搭(示例)。
Go:html.EscapeString(示例)转义五个字符,但引号用数字实体("/',与 PHP 的 "/' 风格不同——语义等价、字节不同);标准库不暴露可编辑表。
Java:JDK 无内置 HTML 转义——Commons Text 的 StringEscapeUtils.escapeHtml4 或手写;示例 Map.of 五字符表 + getOrDefault 扫描。
JavaScript:无转换表 API——惯用 replace + 映射对象一行完成(示例的映射对象就是「那张表」);DOM API 内部的实体机制(textContent vs innerHTML)见 escapehtml 类条目。
Python:html.entities.html5(示例)是标准库直接对应——注意方向与 PHP 相反(实体名→字符),html5 表含 2000+ 具名实体(含 HTML5 新增的);应用层转义是 html.escape;codepoint2name 提供码点→名字视图。
Rust:std 无 HTML 实体——第三方 ammonia/html-escape crate 或手写 match(示例)。
TypeScript:同 JavaScript;映射对象补 as string 类型断言(索引访问的 undefined 收窄)。
教学锚点:「转义函数是黑盒还是白盒」——PHP 是唯一把黑盒打开成白盒的(表可导出可改),Python 的 html.entities 提供反向具名实体全集,其余语言的表要么藏在第三方库要么干脆手写五行;另一个锚点是实体方言:同一个双引号有 "/"/" 三种合法写法,不同语言选了不同的默认(PHP 命名式、Go 数字式)——跨语言对齐转义输出时先对齐方言。