How to Show HTML Special Characters in Textarea

June 15, 2014 Development, PHP

How to Show HTML Special Characters in Textarea

After adding Prism code highlighter to this blog, I quickly found out that all HTML opening angles, which look like <, need to be written in their special character form, or &lt;.

The special character lets the highlighter know that this is not actual markup to be rendered on the page but rather code to be displayed as is. I also found out the special characters would show up as their HTML counterparts in the textarea that I use to edit the posts. Therefore, the &lt; was being displayed as < and would change in the post upon saving.

I turned to dcro2‘s solution on the PHP Freaks forum. He recommended the htmlentities function in PHP.

<textarea><?php echo htmlentities($content); ?></textarea>

This small change was exactly what I was searching for. A quick solution to tell the textarea not to convert the special characters. For a quick example, here’s what the code above looks like in my post editor.

&lt;textarea>&lt;?php echo htmlentities($content); ?>&lt;/textarea>

Although it’s tedious to turn < into &lt; for every single opening and closing tag, it’s a small price to pay for a nice code highlighter that works on all languages.

Let's Talk About Your New Website

View Portfolio Contact Today
Back to Top