Explain Codes LogoExplain Codes Logo

How to display HTML tags as plain text

html
html-escaping
security-best-practices
web-development
Alex KataevbyAlex Kataev·Feb 17, 2025
TLDR

To display HTML tags as plain text, escape the HTML tags by converting < to &lt; and > to &gt;. Instead of being processed as part of your webpage's HTML, they're rendered as text.

Example:

// HTML tag in a suit and tie (just text, ready for a formal event!): &lt;p&gt;Sample text&lt;/p&gt; // Midnight Cinderella, loses the disguise and becomes a charming HTML tag (renders the paragraph): <p>Sample text</p>

This is a really easy way to represent HTML tags as plain text on your web pages.

Higher level methods

Beyond simply escaping < and > characters, there are more established and secure ways to display HTML tags as plain text. These are worth considering:

Wrapping code with pre and code elements

For displaying code blocks, enclose % within <pre> and <code> tags, yes, it's less fun than wrapping a present, but hey, you want to be a coder, right? This approach maintains the formatting and indentation, making physical appearance match functionality. Beauty and brains, all together!

Example:

<pre><code> // Who said code can't be neat and tidy? &lt;div&gt; &lt;p&gt;Hello World!&lt;/p&gt; &lt;/div&gt; </code></pre>

Dealing with form elements

When creating forms and inputs, it's crucial to escape user input, which serves two purposes: making sure your form questions aren't misinterpreted as a marriage proposal, and protecting against XSS attacks.

PHP Example:

// Because a sanitized life is a peaceful life! echo htmlspecialchars($user_input, ENT_QUOTES, 'UTF-8');

Showcasing code structure

Displaying code snippets can often seem like showing an armadillo to a hamster, terrifying and alien. But by combining htmlspecialchars() with <pre> tags, you can present code snippets that maintain their structure and are easier to understand. Let's avoid traumatizing the hamster!

Contextual scenarios

Displaying HTML tags as plain text isn't a banal magic trick, but offers real advantages across various everyday situations:

Web-based tutorials

By showing tags as text, you enable newcomers to learn HTML, which is like directing someone through a maze, while they're blindfolded!

Safeguarding user experience

Imagine their surprise, if users writing "<3" in a chat, suddenly see a heart icon! To prevent such HTML "surprises," use this technique to ensure messages display as intended.

Security enforcement

Defending against malicious attacks is like battling windmills: exciting and necessary in equal measure. Use these techniques to sanitize user-generated content to help keep Don Quixote at bay.

CMS management

In content management systems (CMS), automatic sanitization ensures user-contributed content doesn't choreograph an interpretive dance, but sticks to the script.