minify_html.php 6.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218
  1. <?php
  2. /**
  3. * Class Minify_HTML
  4. * @package Minify
  5. */
  6. /**
  7. * Compress HTML
  8. *
  9. * This is a heavy regex-based removal of whitespace, unnecessary comments and
  10. * tokens. IE conditional comments are preserved. There are also options to have
  11. * STYLE and SCRIPT blocks compressed by callback functions.
  12. *
  13. * A test suite is available.
  14. *
  15. * @package Minify
  16. * @author Stephen Clay <steve@mrclay.org>
  17. */
  18. class Minify_HTML {
  19. /**
  20. * Defines which class to call as part of callbacks, change this
  21. * if you extend Minify_HTML
  22. * @var string
  23. */
  24. protected static $className = 'Minify_HTML';
  25. /**
  26. * "Minify" an HTML page
  27. *
  28. * @param string $html
  29. *
  30. * @param array $options
  31. *
  32. * 'cssMinifier' : (optional) callback function to process content of STYLE
  33. * elements.
  34. *
  35. * 'jsMinifier' : (optional) callback function to process content of SCRIPT
  36. * elements. Note: the type attribute is ignored.
  37. *
  38. * 'xhtml' : (optional boolean) should content be treated as XHTML1.0? If
  39. * unset, minify will sniff for an XHTML doctype.
  40. *
  41. * @return string
  42. */
  43. public static function minify($html, $options = array()) {
  44. if (isset($options['cssMinifier'])) {
  45. self::$_cssMinifier = $options['cssMinifier'];
  46. }
  47. if (isset($options['jsMinifier'])) {
  48. self::$_jsMinifier = $options['jsMinifier'];
  49. }
  50. $html = str_replace("\r\n", "\n", trim($html));
  51. self::$_isXhtml = (
  52. isset($options['xhtml'])
  53. ? (bool)$options['xhtml']
  54. : (false !== strpos($html, '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML'))
  55. );
  56. self::$_replacementHash = 'MINIFYHTML' . md5(time());
  57. self::$_placeholders = array();
  58. // replace SCRIPTs (and minify) with placeholders
  59. $html = preg_replace_callback(
  60. '/\\s*(<script\\b[^>]*?>)([\\s\\S]*?)<\\/script>\\s*/i'
  61. ,array(self::$className, '_removeScriptCB')
  62. ,$html);
  63. // replace STYLEs (and minify) with placeholders
  64. $html = preg_replace_callback(
  65. '/\\s*(<style\\b[^>]*?>)([\\s\\S]*?)<\\/style>\\s*/i'
  66. ,array(self::$className, '_removeStyleCB')
  67. ,$html);
  68. // remove HTML comments (not containing IE conditional comments).
  69. $html = preg_replace_callback(
  70. '/<!--([\\s\\S]*?)-->/'
  71. ,array(self::$className, '_commentCB')
  72. ,$html);
  73. // replace PREs with placeholders
  74. $html = preg_replace_callback('/\\s*(<pre\\b[^>]*?>[\\s\\S]*?<\\/pre>)\\s*/i'
  75. ,array(self::$className, '_removePreCB')
  76. , $html);
  77. // replace TEXTAREAs with placeholders
  78. $html = preg_replace_callback(
  79. '/\\s*(<textarea\\b[^>]*?>[\\s\\S]*?<\\/textarea>)\\s*/i'
  80. ,array(self::$className, '_removeTaCB')
  81. , $html);
  82. // trim each line.
  83. // @todo take into account attribute values that span multiple lines.
  84. $html = preg_replace('/^\\s+|\\s+$/m', '', $html);
  85. // remove ws around block/undisplayed elements
  86. $html = preg_replace('/\\s+(<\\/?(?:area|base(?:font)?|blockquote|body'
  87. .'|caption|center|cite|col(?:group)?|dd|dir|div|dl|dt|fieldset|form'
  88. .'|frame(?:set)?|h[1-6]|head|hr|html|legend|li|link|map|menu|meta'
  89. .'|ol|opt(?:group|ion)|p|param|t(?:able|body|head|d|h||r|foot|itle)'
  90. .'|ul)\\b[^>]*>)/i', '$1', $html);
  91. // remove ws outside of all elements
  92. $html = preg_replace_callback(
  93. '/>([^<]+)</'
  94. ,array(self::$className, '_outsideTagCB')
  95. ,$html);
  96. // use newlines before 1st attribute in open tags (to limit line lengths)
  97. $html = preg_replace('/(<[a-z\\-]+)\\s+([^>]+>)/i', "$1\n$2", $html);
  98. // fill placeholders
  99. $html = str_replace(
  100. array_keys(self::$_placeholders)
  101. ,array_values(self::$_placeholders)
  102. ,$html
  103. );
  104. self::$_placeholders = array();
  105. self::$_cssMinifier = self::$_jsMinifier = null;
  106. return $html;
  107. }
  108. protected static function _commentCB($m)
  109. {
  110. return (0 === strpos($m[1], '[') || false !== strpos($m[1], '<!['))
  111. ? $m[0]
  112. : '';
  113. }
  114. protected static function _reservePlace($content)
  115. {
  116. $placeholder = '%' . self::$_replacementHash . count(self::$_placeholders) . '%';
  117. self::$_placeholders[$placeholder] = $content;
  118. return $placeholder;
  119. }
  120. protected static $_isXhtml = false;
  121. protected static $_replacementHash = null;
  122. protected static $_placeholders = array();
  123. protected static $_cssMinifier = null;
  124. protected static $_jsMinifier = null;
  125. protected static function _outsideTagCB($m)
  126. {
  127. return '>' . preg_replace('/^\\s+|\\s+$/', ' ', $m[1]) . '<';
  128. }
  129. protected static function _removePreCB($m)
  130. {
  131. return self::_reservePlace($m[1]);
  132. }
  133. protected static function _removeTaCB($m)
  134. {
  135. return self::_reservePlace($m[1]);
  136. }
  137. protected static function _removeStyleCB($m)
  138. {
  139. $openStyle = $m[1];
  140. $css = $m[2];
  141. // remove HTML comments
  142. $css = preg_replace('/(?:^\\s*<!--|-->\\s*$)/', '', $css);
  143. // remove CDATA section markers
  144. $css = self::_removeCdata($css);
  145. // minify
  146. $minifier = self::$_cssMinifier
  147. ? self::$_cssMinifier
  148. : 'trim';
  149. $css = call_user_func($minifier, $css);
  150. return self::_reservePlace(self::_needsCdata($css)
  151. ? "{$openStyle}/*<![CDATA[*/{$css}/*]]>*/</style>"
  152. : "{$openStyle}{$css}</style>"
  153. );
  154. }
  155. protected static function _removeScriptCB($m)
  156. {
  157. $openScript = $m[1];
  158. $js = $m[2];
  159. // remove HTML comments (and ending "//" if present)
  160. $js = preg_replace('/(?:^\\s*<!--\\s*|\\s*(?:\\/\\/)?\\s*-->\\s*$)/', '', $js);
  161. // remove CDATA section markers
  162. $js = self::_removeCdata($js);
  163. // minify
  164. $minifier = self::$_jsMinifier
  165. ? self::$_jsMinifier
  166. : 'trim';
  167. $js = call_user_func($minifier, $js);
  168. return self::_reservePlace(self::_needsCdata($js)
  169. ? "{$openScript}/*<![CDATA[*/{$js}/*]]>*/</script>"
  170. : "{$openScript}{$js}</script>"
  171. );
  172. }
  173. protected static function _removeCdata($str)
  174. {
  175. return (false !== strpos($str, '<![CDATA['))
  176. ? str_replace(array('<![CDATA[', ']]>'), '', $str)
  177. : $str;
  178. }
  179. protected static function _needsCdata($str)
  180. {
  181. return (self::$_isXhtml && preg_match('/(?:[<&]|\\-\\-|\\]\\]>)/', $str));
  182. }
  183. }