Skip to content

Instantly share code, notes, and snippets.

@feeela
Last active August 21, 2018 15:28
Show Gist options
  • Save feeela/7355668 to your computer and use it in GitHub Desktop.
Save feeela/7355668 to your computer and use it in GitHub Desktop.
Add CDATA to script- and style-tags via regex using PHPs output buffering
<?php
/* do this if MIME type is 'application/xhtml+xml' */
ob_start(function ($buffer) {
$replacer = array(
'/(<script[^<>]*>)([^<>]+)(<\/script>)/' => '$1<![CDATA[ $2 ]]>$3',
'/(<style[^<>]*>)([^<>]+)(<\/style>)/' => '$1<![CDATA[ $2 ]]>$3',
/* more replaces may follow, like:
* replace ampersand-characters, which are not part of an entity or within a CDATA-block
'/&(?!(?:[a-zA-Z][a-zA-Z0-9]*|#\d+);)(?!(?>(?:(?!<!\[CDATA\[|\]\]>).)*)\]\]>)/s' => '&#38;',
* replace html-entities with xml entities
'/&nbsp;/' => '&#160;',
*/
);
return preg_replace(array_keys($replacer), array_values($replacer), $buffer);
});
/* a script-block like
<script type="text/javascript">
$(document).ready(function() {
$('.hover').bind('touchstart touchend', function(e) {
e.preventDefault();
$(this).toggleClass('hover_effect');
});
});
</script>
* will translate to
<script type="text/javascript"><![CDATA[
$(document).ready(function() {
$('.hover').bind('touchstart touchend', function(e) {
e.preventDefault();
$(this).toggleClass('hover_effect');
});
});
]]></script>
*/
@feeela
Copy link
Author

feeela commented Oct 8, 2015

Add CDATA to script- and style-tags via regex using PHPs output buffering

This snippet can be used to sanitize HTML when delivering it as XHTML. Everything (at least there must be one character) between script/style-tags is enclosed by a CDATA-block.

The whole functionality is provided as a callback function to ob_start(), which should be used before any output. The use of ob_flush(), ob_clean() or something is optional as the buffer will be sent on script end anyway.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment