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


/ Published in: PHP
Save to your folder(s)

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.


Copy this code and paste it in your HTML
  1. // do this if MIME type is 'application/xhtml+xml'
  2. ob_start(function ($buffer) {
  3. $replacer = array(
  4. '/(<script[^<>]*>)([^<>]+)(<\/script>)/' => '$1<![CDATA[ $2 ]]>$3',
  5. '/(<style[^<>]*>)([^<>]+)(<\/style>)/' => '$1<![CDATA[ $2 ]]>$3',
  6. /* more replaces may follow, like:
  7.  * replace ampersand-characters, which are not part of an entity or within a CDATA-block
  8. '/&(?!(?:[a-zA-Z][a-zA-Z0-9]*|#\d+);)(?!(?>(?:(?!<!\[CDATA\[|\]\]>).)*)\]\]>)/s' => '&#38;',
  9.  * replace html-entities with xml entities
  10. '/&nbsp;/' => '&#160;',
  11.  */
  12. );
  13. return preg_replace(array_keys($replacer), array_values($replacer), $buffer);
  14. });
  15.  
  16. /* a script-block like
  17.  
  18. <script type="text/javascript">
  19. $(document).ready(function() {
  20. $('.hover').bind('touchstart touchend', function(e) {
  21. e.preventDefault();
  22. $(this).toggleClass('hover_effect');
  23. });
  24. });
  25. </script>
  26.  
  27.  * will translate to
  28.  
  29. <script type="text/javascript"><![CDATA[
  30. $(document).ready(function() {
  31. $('.hover').bind('touchstart touchend', function(e) {
  32. e.preventDefault();
  33. $(this).toggleClass('hover_effect');
  34. });
  35. });
  36. ]]></script>
  37.  
  38.  */

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.