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

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("&lt;");
        else if (*p == '>') printf("&gt;");
        else if (*p == '&') printf("&amp;");
        else if (*p == '"') printf("&quot;");
        else if (*p == '\'') printf("&#039;");
        else putchar(*p);
    }
    printf("\n");
    return 0;
}
Output
&lt;b&gt;Tom &amp; Jerry&lt;/b&gt;

C++ C++26

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 += "&lt;"; break;
        case '>': out += "&gt;"; break;
        case '&': out += "&amp;"; break;
        case '"': out += "&quot;"; break;
        case '\'': out += "&#039;"; break;
        default: out += c;
        }
    }
    return out;
}

int main() {
    std::cout << escape_html("<b>Tom & Jerry</b>") << "\n";
    return 0;
}
Output
&lt;b&gt;Tom &amp; Jerry&lt;/b&gt;

C# v11.0.100

v11.0.100
using System.Net;
Console.WriteLine(WebUtility.HtmlEncode("<b>Tom & Jerry</b>")); // note: quotes are not escaped
Output
&lt;b&gt;Tom &amp; Jerry&lt;/b&gt;

Go v1.27.4

v1.27.4
package main

import (
	"fmt"
	"html"
)

func main() {
	fmt.Println(html.EscapeString("<b>Tom & Jerry</b>")) // escapes the five characters & < > " '
}
Output
&lt;b&gt;Tom &amp; Jerry&lt;/b&gt;

Java v27.0.1

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("&", "&amp;")
                .replace("<", "&lt;")
                .replace(">", "&gt;")
                .replace("\"", "&quot;")
                .replace("'", "&#039;");
    }

    public static void main(String[] args) {
        System.out.println(escapeHtml("<b>Tom & Jerry</b>"));
    }
}
Output
&lt;b&gt;Tom &amp; Jerry&lt;/b&gt;

JavaScript v26.13.1

v26.13.1
// no standard-library escaping; the idiomatic replace chain (& first)
const escapeHtml = (s) => s
  .replaceAll("&", "&amp;")
  .replaceAll("<", "&lt;")
  .replaceAll(">", "&gt;")
  .replaceAll('\"', "&quot;")
  .replaceAll("'", "&#039;");
console.log(escapeHtml("<b>Tom & Jerry</b>"));
Output
&lt;b&gt;Tom &amp; Jerry&lt;/b&gt;

PHP v8.6.0

v8.6.0
echo htmlspecialchars('<b class="x">Tom & Jerry</b>'); // PHP 8.1+ includes ENT_QUOTES by default
Output
&lt;b class=&quot;x&quot;&gt;Tom &amp; Jerry&lt;/b&gt;

Python v3.15.2

v3.15.2
from html import escape
print(escape('<b>Tom & Jerry</b>'))  # quote=True escapes quotes too by default
Output
&lt;b&gt;Tom &amp; Jerry&lt;/b&gt;

Rust v1.99.1

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("&lt;"),
            '>' => out.push_str("&gt;"),
            '&' => out.push_str("&amp;"),
            '"' => out.push_str("&quot;"),
            '\'' => out.push_str("&#039;"),
            _ => out.push(c),
        }
    }
    out
}

fn main() {
    println!("{}", escape_html("<b>Tom & Jerry</b>"));
}
Output
&lt;b&gt;Tom &amp; Jerry&lt;/b&gt;

TypeScript v26.13.1

v26.13.1
// no standard-library escaping; the idiomatic replace chain (& first)
const escapeHtml = (s: string): string => s
  .replaceAll("&", "&amp;")
  .replaceAll("<", "&lt;")
  .replaceAll(">", "&gt;")
  .replaceAll('\"', "&quot;")
  .replaceAll("'", "&#039;");
console.log(escapeHtml("<b>Tom & Jerry</b>"));
Output
&lt;b&gt;Tom &amp; Jerry&lt;/b&gt;

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 &#x27;), 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.