Return to Snippet

Revision: 43884
at April 2, 2011 01:22 by feeela


Initial Code
// 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>

 */

Initial URL


Initial Description
This snippet can be used to sanitize HTML when delivering it as XHTML. For example Firefox 2 needs XML-data to not mess up with HTML5-tags.
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.

Initial Title
add CDATA to script- and style-tags via regex using PHPs output buffering

Initial Tags


Initial Language
PHP