Last active
August 21, 2018 15:28
-
-
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
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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' => '&', | |
* replace html-entities with xml entities | |
'/ /' => ' ', | |
*/ | |
); | |
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> | |
*/ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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.