escapeHtml
Escapes HTML special characters to their corresponding entities to prevent HTML injection while preserving UTF-8.
Behavior
- Converts
<,>,&,\",'and other special characters to HTML entities. - Uses
ENT_QUOTES | ENT_HTML5 | ENT_SUBSTITUTEwithUTF-8to avoid corrupting multibyte text and to substitute invalid bytes. - Escapes quotes for attribute contexts; suitable for both element content and attribute values.
- Multibyte-safe and suitable for HTML contexts.
Usage
echo SM::escapeHtml('<script>alert("XSS")</script>');
// <script>alert("XSS")</script>
echo SM::make(' <b>hello</b> ')
->trim()
->escapeHtml();
// <b>hello</b>
Examples
$title = 'Click "here" & learn';
echo (string)SM::escapeHtml($title);
// Click "here" & learn
echo SM::escapeHtml(null);
// '' (empty string)
echo SM::escapeHtml('Café Münster <em>x</em>');
// Café Münster <em>x</em>
Technical notes
- Implementation uses
htmlspecialchars($input, ENT_QUOTES | ENT_HTML5 | ENT_SUBSTITUTE, 'UTF-8'). - Designed to preserve UTF-8 text and avoid breaking accented characters.