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:
http://www.thatsquality.com/articles/how-to-match-and-replace-content-between-two-html-tags-using-regular-expressions
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
as your output; and$content
as the HTML with <code> tags that you need to encode.
$content_processed = preg_replace_callback(
'#\<code\>(.+?)\<\/code\>#s',
create_function(
'$matches',
'return "<"."code".">".str_replace("\t", " ", nl2br(htmlentities($matches[1])))."<"./code.">";'
),
$content
);
echo $content_processed;
The call back function will do 3 things to the data:
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.
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.
Follow me: @andrewsirianni
Copyright ©2012 Andrew Sirianni, All Rights Reserved LinkedIn Profile