minify_html_function.php
1 <?php
2
/**
3  * Minify html
4  *
5  * Based on PeecFW HTMLCompressor
6  *
7  * @param string $html HTML content to be minified
8  * 
9  * @return string minified HTML content
10  */
11
function minify_html_function($html) {
12     if ( ! 
strstr($html'<html') || ! strstr($html'</html>')) {
13         return 
$html;
14     }
15     
16     
preg_match_all("!<style[^>]+>.*?</style>!is"$html$match);
17     
$styles $match[0];
18
19     
preg_match_all("!<script[^>][^<src>]+>.*?</script>!is"$html$match); // Modified, do not skip script tags with src in it..
20     
$scripts $match[0];
21
22     
preg_match_all("!<pre[^>]*>.*?</pre>!is"$html$match);
23     
$pre $match[0];
24
25     
preg_match_all("!<textarea[^>]+>.*?</textarea>!is"$html$match);
26     
$textareas $match[0];
27
28     
$search = array("!<style[^>]+>.*?</style>!is""!<script[^>][^<src>]+>.*?</script>!is""!<pre[^>]*>.*?</pre>!is""!<textarea[^>]+>.*?</textarea>!is");
29     
$replace = array('@TRIM:STYLE@''@TRIM:SCRIPT@''@TRIM:PRE@''@TRIM:TEXTAREA@');
30
31     
$html str_replace('<br>''<br />'$html); // XHTML valid br tags must be done
32     
$html str_replace('<BR>''<br />'$html); // XHTML valid br tags must be done
33     
$html trim(preg_replace(array('/((?<!\?>)\n)[\s]+/m''/\>\s+\</'), array('\1''><'), $html));
34
35     
// Printer library relys on comment
36     //$html = preg_replace('/<!--[^<[if>](.|\s)*?-->/', '', $html);   // Remove html comments...
37
38     
$html preg_replace($search$replace$html);
39
40     
$searches = array('@TRIM:STYLE@' => $styles'@TRIM:SCRIPT@' => $scripts'@TRIM:PRE@' => $pre'@TRIM:TEXTAREA@' => $textareas);
41
42     foreach (
$searches as $search => $replace ) {
43         
$len strlen($search);
44         
$pos 0;
45         
$count count($replace);
46
47         if (
$count 1){
48             continue;
49         }
50
51         for (
$i 0$i $count$i++) {
52             if ((
$pos strpos($html$search$pos)) !== FALSE) {
53                 
$html substr_replace($html$replace[$i], $pos$len);
54             } else {
55                 continue;
56             }
57         }
58     } 
59
60     return 
$html;
61 }
62
63
/* End of file: ./system/functions/minify_html/minify_html_function.php */
64

Page URI: http://www.infopotato.com/index.php/code/function/minify_html/