HTML.php 8.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256
  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. * @var boolean
  21. */
  22. protected $_jsCleanComments = true;
  23. /**
  24. * "Minify" an HTML page
  25. *
  26. * @param string $html
  27. *
  28. * @param array $options
  29. *
  30. * 'cssMinifier' : (optional) callback function to process content of STYLE
  31. * elements.
  32. *
  33. * 'jsMinifier' : (optional) callback function to process content of SCRIPT
  34. * elements. Note: the type attribute is ignored.
  35. *
  36. * 'xhtml' : (optional boolean) should content be treated as XHTML1.0? If
  37. * unset, minify will sniff for an XHTML doctype.
  38. *
  39. * @return string
  40. */
  41. public static function minify($html, $options = array()) {
  42. $min = new self($html, $options);
  43. return $min->process();
  44. }
  45. /**
  46. * Create a minifier object
  47. *
  48. * @param string $html
  49. *
  50. * @param array $options
  51. *
  52. * 'cssMinifier' : (optional) callback function to process content of STYLE
  53. * elements.
  54. *
  55. * 'jsMinifier' : (optional) callback function to process content of SCRIPT
  56. * elements. Note: the type attribute is ignored.
  57. *
  58. * 'jsCleanComments' : (optional) whether to remove HTML comments beginning and end of script block
  59. *
  60. * 'xhtml' : (optional boolean) should content be treated as XHTML1.0? If
  61. * unset, minify will sniff for an XHTML doctype.
  62. */
  63. public function __construct($html, $options = array())
  64. {
  65. $this->_html = str_replace("\r\n", "\n", trim($html));
  66. if (isset($options['xhtml'])) {
  67. $this->_isXhtml = (bool)$options['xhtml'];
  68. }
  69. if (isset($options['cssMinifier'])) {
  70. $this->_cssMinifier = $options['cssMinifier'];
  71. }
  72. if (isset($options['jsMinifier'])) {
  73. $this->_jsMinifier = $options['jsMinifier'];
  74. }
  75. if (isset($options['jsCleanComments'])) {
  76. $this->_jsCleanComments = (bool)$options['jsCleanComments'];
  77. }
  78. }
  79. /**
  80. * Minify the markeup given in the constructor
  81. *
  82. * @return string
  83. */
  84. public function process()
  85. {
  86. if ($this->_isXhtml === null) {
  87. $this->_isXhtml = (false !== strpos($this->_html, '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML'));
  88. }
  89. $this->_replacementHash = 'MINIFYHTML' . md5($_SERVER['REQUEST_TIME']);
  90. $this->_placeholders = array();
  91. // replace SCRIPTs (and minify) with placeholders
  92. $this->_html = preg_replace_callback(
  93. '/(\\s*)<script(\\b[^>]*?>)([\\s\\S]*?)<\\/script>(\\s*)/i'
  94. ,array($this, '_removeScriptCB')
  95. ,$this->_html);
  96. // replace STYLEs (and minify) with placeholders
  97. $this->_html = preg_replace_callback(
  98. '/\\s*<style(\\b[^>]*>)([\\s\\S]*?)<\\/style>\\s*/i'
  99. ,array($this, '_removeStyleCB')
  100. ,$this->_html);
  101. // remove HTML comments (not containing IE conditional comments).
  102. $this->_html = preg_replace_callback(
  103. '/<!--([\\s\\S]*?)-->/'
  104. ,array($this, '_commentCB')
  105. ,$this->_html);
  106. // replace PREs with placeholders
  107. $this->_html = preg_replace_callback('/\\s*<pre(\\b[^>]*?>[\\s\\S]*?<\\/pre>)\\s*/i'
  108. ,array($this, '_removePreCB')
  109. ,$this->_html);
  110. // replace TEXTAREAs with placeholders
  111. $this->_html = preg_replace_callback(
  112. '/\\s*<textarea(\\b[^>]*?>[\\s\\S]*?<\\/textarea>)\\s*/i'
  113. ,array($this, '_removeTextareaCB')
  114. ,$this->_html);
  115. // trim each line.
  116. // @todo take into account attribute values that span multiple lines.
  117. $this->_html = preg_replace('/^\\s+|\\s+$/m', '', $this->_html);
  118. // remove ws around block/undisplayed elements
  119. $this->_html = preg_replace('/\\s+(<\\/?(?:area|base(?:font)?|blockquote|body'
  120. .'|caption|center|col(?:group)?|dd|dir|div|dl|dt|fieldset|form'
  121. .'|frame(?:set)?|h[1-6]|head|hr|html|legend|li|link|map|menu|meta'
  122. .'|ol|opt(?:group|ion)|p|param|t(?:able|body|head|d|h||r|foot|itle)'
  123. .'|ul)\\b[^>]*>)/i', '$1', $this->_html);
  124. // remove ws outside of all elements
  125. $this->_html = preg_replace(
  126. '/>(\\s(?:\\s*))?([^<]+)(\\s(?:\s*))?</'
  127. ,'>$1$2$3<'
  128. ,$this->_html);
  129. // use newlines before 1st attribute in open tags (to limit line lengths)
  130. $this->_html = preg_replace('/(<[a-z\\-]+)\\s+([^>]+>)/i', "$1\n$2", $this->_html);
  131. // fill placeholders
  132. $this->_html = str_replace(
  133. array_keys($this->_placeholders)
  134. ,array_values($this->_placeholders)
  135. ,$this->_html
  136. );
  137. // issue 229: multi-pass to catch scripts that didn't get replaced in textareas
  138. $this->_html = str_replace(
  139. array_keys($this->_placeholders)
  140. ,array_values($this->_placeholders)
  141. ,$this->_html
  142. );
  143. return $this->_html;
  144. }
  145. protected function _commentCB($m)
  146. {
  147. return (0 === strpos($m[1], '[') || false !== strpos($m[1], '<!['))
  148. ? $m[0]
  149. : '';
  150. }
  151. protected function _reservePlace($content)
  152. {
  153. $placeholder = '%' . $this->_replacementHash . count($this->_placeholders) . '%';
  154. $this->_placeholders[$placeholder] = $content;
  155. return $placeholder;
  156. }
  157. protected $_isXhtml = null;
  158. protected $_replacementHash = null;
  159. protected $_placeholders = array();
  160. protected $_cssMinifier = null;
  161. protected $_jsMinifier = null;
  162. protected function _removePreCB($m)
  163. {
  164. return $this->_reservePlace("<pre{$m[1]}");
  165. }
  166. protected function _removeTextareaCB($m)
  167. {
  168. return $this->_reservePlace("<textarea{$m[1]}");
  169. }
  170. protected function _removeStyleCB($m)
  171. {
  172. $openStyle = "<style{$m[1]}";
  173. $css = $m[2];
  174. // remove HTML comments
  175. $css = preg_replace('/(?:^\\s*<!--|-->\\s*$)/', '', $css);
  176. // remove CDATA section markers
  177. $css = $this->_removeCdata($css);
  178. // minify
  179. $minifier = $this->_cssMinifier
  180. ? $this->_cssMinifier
  181. : 'trim';
  182. $css = call_user_func($minifier, $css);
  183. return $this->_reservePlace($this->_needsCdata($css)
  184. ? "{$openStyle}/*<![CDATA[*/{$css}/*]]>*/</style>"
  185. : "{$openStyle}{$css}</style>"
  186. );
  187. }
  188. protected function _removeScriptCB($m)
  189. {
  190. $openScript = "<script{$m[2]}";
  191. $js = $m[3];
  192. // whitespace surrounding? preserve at least one space
  193. $ws1 = ($m[1] === '') ? '' : ' ';
  194. $ws2 = ($m[4] === '') ? '' : ' ';
  195. // remove HTML comments (and ending "//" if present)
  196. if ($this->_jsCleanComments) {
  197. $js = preg_replace('/(?:^\\s*<!--\\s*|\\s*(?:\\/\\/)?\\s*-->\\s*$)/', '', $js);
  198. }
  199. // remove CDATA section markers
  200. $js = $this->_removeCdata($js);
  201. // minify
  202. $minifier = $this->_jsMinifier
  203. ? $this->_jsMinifier
  204. : 'trim';
  205. $js = call_user_func($minifier, $js);
  206. return $this->_reservePlace($this->_needsCdata($js)
  207. ? "{$ws1}{$openScript}/*<![CDATA[*/{$js}/*]]>*/</script>{$ws2}"
  208. : "{$ws1}{$openScript}{$js}</script>{$ws2}"
  209. );
  210. }
  211. protected function _removeCdata($str)
  212. {
  213. return (false !== strpos($str, '<![CDATA['))
  214. ? str_replace(array('<![CDATA[', ']]>'), '', $str)
  215. : $str;
  216. }
  217. protected function _needsCdata($str)
  218. {
  219. return ($this->_isXhtml && preg_match('/(?:[<&]|\\-\\-|\\]\\]>)/', $str));
  220. }
  221. }