Encode HTML Entities Within Your <code> Tags



Apache/2.4.18 (Ubuntu) Server at dcode.com.au Port 80
" data-via="andrewsirianni">Tweet

In an earlier post, I wrote about compressing your HTML output through Savant3. However, a by-product of this process is that you loose the line breaks and tabs within your <code> tags. To solve this, I have adapted a script originally written by "Ryan" to ensure that everything within the <code> tag is replaced with htmlentities. This script is useful if you're using my Savant3 compressor, or simply if you need to encode your code snippets.

The original code/article can be found at:

The function will use preg_replace_callback to search for all <code> elements and return the encoded string in its place.

The function assumes the following variables:

$content_processed = preg_replace_callback(
    'return "<"."code".">".str_replace("\t", " &nbsp; ", nl2br(htmlentities($matches[1])))."<"./code.">";'

echo $content_processed;

The call back function will do 3 things to the data:

  1. Encode the html with htmlentites; then
  2. Convert the line breaks to <br> tags; then
  3. Convert the tabs to encoded tabs.

To find out more about how the regular expression works, please read Ryan's post.

I hope you find this useful! Please share your feedback and comments.

comments powered by Disqus

About Me

I design & develop software that runs on the Internet. As a qualified analyst, accountant and real estate agent, I can deploy systems that improve performance.


Warning: DOMDocument::load(https://api.twitter.com/1/statuses/user_timeline.rss?screen_name=andrewsirianni&count=5): failed to open stream: HTTP request failed! HTTP/1.0 410 Gone in /home/andrxvjf/public_etc/templates/rmargin/twitter.tpl.php on line 8

Warning: DOMDocument::load(): I/O warning : failed to load external entity "https://api.twitter.com/1/statuses/user_timeline.rss?screen_name=andrewsirianni&count=5" in /home/andrxvjf/public_etc/templates/rmargin/twitter.tpl.php on line 8

Recent Tweets

Follow me: @andrewsirianni

Copyright ©2012 Andrew Sirianni, All Rights Reserved   LinkedIn Profile