Display Sample HTML By Escaping < and > Characters

So you’ve decided that <xmp> and <textarea> aren’t working for you. What’s the best, most versatile option?

Escape all of the < and > characters so that the browser will display them, instead of rendering the HTML.

There are several characters that have “escaped” forms, meaning that you enter a special code so that the browser will display them rather than render them as something special.

For example, &lt; will be displayed as < and &gt; will be displayed as >. [Incidentally, if you’d like to display &lt;, you need to use &amp; to display the &]

What this means for us is that we can replace every < and > in our HTML with the escaped versions. The browser won’t see the text as HTML tags - it’ll simply see a bunch of characters to display.

Here’s an example:

&lt;p&gt;Here's some &lt;strong&gt;
  sample&lt;/strong&gt; text.&lt;/p&gt;
&lt;p&gt;You'll see &lt;em&gt;all&lt;/em&gt;
  of the tags.&lt;/p&gt;

If you put this in an HTML file, it would be displayed as:

<p>Here’s some <strong>sample</strong> text.</p>
<p>You’ll see <em>all</em> of the tags.</p>

A big advantage of this method is that you can print the text in a <pre> and/or <code> tag and style it. You could also use <span> tags to add color and syntax highlighting.

This is clearly the most versatile and sure-fire way to make your HTML display the way you want it to. The problem, though, is that you need to convert every < and > in the bit of sample text.

If it’s a short piece, that’s no big deal. If you’re trying to show a longer example, it might take a long time to convert, and it could be easy to mess up.

Don’t worry. There’s a solution for that too. You can head over to this tool I created to escape the characters for you. Simply copy and paste your sample HTML into the first <textarea> and the script will do the rest.

Alternatively, you could use the php function htmlentities() or htmlspecialchars(). If you’re blogging platform or CMS easily allows you to integrate php, these functions will automatically escape the characters for you as well.

Last step? Learn to style your sample code.

Go back to the main guide: How to Display Sample HTML


Bookmark and Share:
These icons link to social bookmarking sites where readers can share and discover new web pages.

  • Digg
  • Furl
  • del.icio.us
  • StumbleUpon
  • MisterWong
  • DZone
  • Technorati

Leave a Reply