htmlspecialchars
htmlspecialchars(string $string, int $flags = ENT_QUOTES | ENT_SUBSTITUTE | ENT_HTML401, ?string $encoding = null, bool $double_encode = true): string
Converts HTML-sensitive characters (& < > quotes) to entities — the first line of defense against XSS.
C C23
#include <stdio.h>
// replace the five HTML-sensitive characters & < > " ' char by char
int main(void) {
const char *s = "<b>Tom & Jerry</b>";
for (const char *p = s; *p; p++) {
if (*p == '<') printf("<");
else if (*p == '>') printf(">");
else if (*p == '&') printf("&");
else if (*p == '"') printf(""");
else if (*p == '\'') printf("'");
else putchar(*p);
}
printf("\n");
return 0;
}
<b>Tom & Jerry</b>
C++ C++26
#include <iostream>
#include <string>
// replace the five HTML-sensitive characters & < > " ' char by char
std::string escape_html(const std::string &s) {
std::string out;
for (char c : s) {
switch (c) {
case '<': out += "<"; break;
case '>': out += ">"; break;
case '&': out += "&"; break;
case '"': out += """; break;
case '\'': out += "'"; break;
default: out += c;
}
}
return out;
}
int main() {
std::cout << escape_html("<b>Tom & Jerry</b>") << "\n";
return 0;
}
<b>Tom & Jerry</b>
C# v11.0.100
using System.Net;
Console.WriteLine(WebUtility.HtmlEncode("<b>Tom & Jerry</b>")); // note: quotes are not escaped
<b>Tom & Jerry</b>
Go v1.27.4
package main
import (
"fmt"
"html"
)
func main() {
fmt.Println(html.EscapeString("<b>Tom & Jerry</b>")) // escapes the five characters & < > " '
}
<b>Tom & Jerry</b>
Java v27.0.1
public class Main {
// no HTML escaping in the standard library; a replace chain does minimal escaping (& must go first)
static String escapeHtml(String s) {
return s.replace("&", "&")
.replace("<", "<")
.replace(">", ">")
.replace("\"", """)
.replace("'", "'");
}
public static void main(String[] args) {
System.out.println(escapeHtml("<b>Tom & Jerry</b>"));
}
}
<b>Tom & Jerry</b>
JavaScript v26.13.1
// no standard-library escaping; the idiomatic replace chain (& first)
const escapeHtml = (s) => s
.replaceAll("&", "&")
.replaceAll("<", "<")
.replaceAll(">", ">")
.replaceAll('\"', """)
.replaceAll("'", "'");
console.log(escapeHtml("<b>Tom & Jerry</b>"));
<b>Tom & Jerry</b>
PHP v8.6.0
echo htmlspecialchars('<b class="x">Tom & Jerry</b>'); // PHP 8.1+ includes ENT_QUOTES by default
<b class="x">Tom & Jerry</b>
Python v3.15.2
from html import escape
print(escape('<b>Tom & Jerry</b>')) # quote=True escapes quotes too by default
<b>Tom & Jerry</b>
Rust v1.99.1
// no standard-library escaping; hand-written char-by-char replacement (& < > " ')
fn escape_html(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() {
println!("{}", escape_html("<b>Tom & Jerry</b>"));
}
<b>Tom & Jerry</b>
TypeScript v26.13.1
// no standard-library escaping; the idiomatic replace chain (& first)
const escapeHtml = (s: string): string => s
.replaceAll("&", "&")
.replaceAll("<", "<")
.replaceAll(">", ">")
.replaceAll('\"', """)
.replaceAll("'", "'");
console.log(escapeHtml("<b>Tom & Jerry</b>"));
<b>Tom & Jerry</b>
Language differences
C: no HTML tooling at all — replace the five sensitive characters char by char (example); & must be replaced too, otherwise double encoding breaks round-trips.
C++: the same hand-written switch replacement as C (example); keep the standard-library hand-rolled version — third-party template engines usually ship their own escaping.
C#: WebUtility.HtmlEncode covers & < > and a few others but not quotes — before placing into an HTML attribute (value="...") switch to System.Text.Encodings.Web.HtmlEncoder.Default (which also escapes quotes and non-ASCII).
Go: html.EscapeString escapes all five sensitive characters (example), safe for attribute context directly; in templating use html/template (context-aware auto-escaping).
Java: the standard library has no HTML escaping — a replace chain is hand-written (example), with & first to prevent double escaping; Apache Commons Text StringEscapeUtils.escapeHtml4 is the common third-party pick.
JavaScript: no standard-library escape (in browsers you can round-trip via DOM textContent + innerHTML; in Node the replace chain is hand-written, as in the example); the key point: escape functions map one-to-one to contexts — entity-escape for HTML text, quotes+entities for attributes, and inside <script> guard </script> breakouts (JSON-serialize and replace <), URLs use encodeURIComponent — one function does not fit all.
PHP: htmlspecialchars escapes & < > " ' (8.1+ default flags include ENT_QUOTES; older defaults left single quotes intact); ENT_SUBSTITUTE turns malformed UTF-8 into replacement chars instead of empty strings (a safe default); see the htmlentities entry for the difference.
Python: html.escape escapes quotes by default (quote=True, example, single quotes to '), safe for both element and attribute context.
Rust: none in the standard library — hand-written char-by-char replacement (example); web stacks usually rely on template engines like askama/maud for automatic escaping.
TypeScript: same as JavaScript; once contexts are separated, wrap escapeHtml/escapeAttr/escapeJs as three functions.