PluginProbe
WP Coder – Insert & Manage Code Snippets / 4.4
WP Coder – Insert & Manage Code Snippets v4.4
4.5.1 1.1 2.3.1 2.3.2 2.4.1 2.5.1 2.5.2 2.5.3 2.5.4 2.5.5 2.5.6 3.0 3.0.1 3.0.2 3.0.3 3.0.4 3.0.5 3.1 3.1.1 3.2 3.2.1 3.3 3.4 3.5 3.5.1 All 39 releases
wp-coder / classes / Optimization / HTMLMinifier.php

HTMLMinifier.php in WP Coder – Insert & Manage Code Snippets 4.4, at classes/Optimization/HTMLMinifier.php

57 lines 1.7 KB
No matching file
Up and down to move Enter to open Esc to close
Raw Download Zip
1 <?php
2
3 namespace WPCoder\Optimization;
4
5 class HTMLMinifier {
6
7 public static function minify( $input ): string {
8 if ( trim( $input ) === "" ) {
9 return $input;
10 }
11 // Remove extra white-space(s) between HTML attribute(s)
12 $input = preg_replace_callback( '#<([^\/\s<>!]+)(?:\s+([^<>]*?)\s*|\s*)(\/?)>#s', function ( $matches ) {
13 return '<' . $matches[1] . preg_replace( '#([^\s=]+)(\=([\'"]?)(.*?)\3)?(\s+|$)#s', ' $1$2', $matches[2] ) . $matches[3] . '>';
14 }, str_replace( "\r", "", $input ) );
15
16 return preg_replace(
17 array(
18 // t = text
19 // o = tag open
20 // c = tag close
21 // Keep important white-space(s) after self-closing HTML tag(s)
22 '#<(img|input)(>| .*?>)#s',
23 // Remove a line break and two or more white-space(s) between tag(s)
24 '#(<!--.*?-->)|(>)(?:\n*|\s{2,})(<)|^\s*|\s*$#s',
25 '#(<!--.*?-->)|(?<!\>)\s+(<\/.*?>)|(<[^\/]*?>)\s+(?!\<)#s',
26 // t+c || o+t
27 '#(<!--.*?-->)|(<[^\/]*?>)\s+(<[^\/]*?>)|(<\/.*?>)\s+(<\/.*?>)#s',
28 // o+o || c+c
29 '#(<!--.*?-->)|(<\/.*?>)\s+(\s)(?!\<)|(?<!\>)\s+(\s)(<[^\/]*?\/?>)|(<[^\/]*?\/?>)\s+(\s)(?!\<)#s',
30 // c+t || t+o || o+t -- separated by long white-space(s)
31 '#(<!--.*?-->)|(<[^\/]*?>)\s+(<\/.*?>)#s',
32 // empty tag
33 '#<(img|input)(>| .*?>)<\/\1>#s',
34 // reset previous fix
35 '#(&nbsp;)&nbsp;(?![<\s])#',
36 // clean up ...
37 '#(?<=\>)(&nbsp;)(?=\<)#',
38 // --ibid
39 // Remove HTML comment(s) except IE and noindex comment(s)
40 '#\s*<!--(?!(\[if\s)|(noindex)|(\/noindex)).*?-->\s*|(?<!\>)\n+(?=\<[^!])#s',
41 //'#\s*<!--(?!\[if\s).*?-->\s*|(?<!\>)\n+(?=\<[^!])#s' - noindex fix
42 ),
43 array(
44 '<$1$2</$1>',
45 '$1$2$3',
46 '$1$2$3',
47 '$1$2$3$4$5',
48 '$1$2$3$4$5$6$7',
49 '$1$2$3',
50 '<$1$2',
51 '$1 ',
52 '$1',
53 ""
54 ),
55 $input );
56 }
57 }