HTML tags to print on page by htmlspecialchars function

Escape text before inserting it into HTML

Use htmlspecialchars() when untrusted or variable text is placed into normal HTML text or attribute contexts. Escaping is an output step: keep the original data unchanged and escape it for the context where it is rendered.

$input = '<strong>Tom & Jerry</strong>';
echo htmlspecialchars($input, ENT_QUOTES | ENT_SUBSTITUTE, 'UTF-8');

The examples below show additional variations, expected output and practical usage.

Rendered as HTML, the tags in the sample affect presentation:

Hello this is bold This is italic This is normal this is a double quote " this is & this is less than < this is greater than >

To show the markup itself as text, escape it before inserting it into the page:

$sample = '<b>Hello this is bold</b> <i>This is italic</i>';
echo htmlspecialchars($sample, ENT_QUOTES | ENT_SUBSTITUTE, 'UTF-8');

The browser then displays the angle brackets instead of interpreting them as HTML.

<b>Hello this is bold</b> <i>This is italic</i>

Characters handled by htmlspecialchars()

By default, htmlspecialchars() converts characters that have special meaning in HTML, including &, <, > and quotes according to the selected flags. For modern UTF-8 pages, explicitly passing ENT_QUOTES | ENT_SUBSTITUTE and 'UTF-8' makes the intended behavior clear.


Example: Escaping User Input for HTML Output

$input = "<script>alert('XSS');</script>";
$escaped_input = htmlspecialchars($input, ENT_QUOTES | ENT_SUBSTITUTE, 'UTF-8');
echo $escaped_input; // <script>alert(&#039;XSS&#039;);</script>

Example: Handling Special Characters

$str = 'Hello & welcome!';
echo htmlspecialchars($str);  // Output: Hello & welcome!

Example: Comparing htmlspecialchars() and htmlentities()

$str = '© 2023 Plus2Net';
echo htmlspecialchars($str);  // Output: © 2023 Plus2Net
echo htmlentities($str);  // Output: © 2023 Plus2Net
These examples show how HTML output escaping preserves text safely for display. Escaping is context-specific and should not be confused with changing or sanitizing the stored input.

HTML tags and character entities
String Functions Remove HTML tags


Subscribe to our YouTube Channel here



plus2net.com







webchecker

17-02-2010

very good explanation, thank you




PHP video Tutorials
✖
We use cookies to improve your browsing experience. . Learn more
HTML MySQL PHP JavaScript ASP Photoshop Articles Contact us
© 2000-2026 plus2net.com All rights reserved worldwide Privacy Policy Disclaimer