Last active
December 5, 2017 00:41
-
-
Save shinmai/add32c1c61750fb6dd58cbf0525b4a9a to your computer and use it in GitHub Desktop.
Wordpress HTML-minifying
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* Warwick | |
* Very small HTML from WordPress. Place at the end of your theme's functions.php | |
* @version 0.8.0 | |
* @link https://gist.github.com/shinmai/add32c1c61750fb6dd58cbf0525b4a9a | |
* @license http://www.wtfpl.net/txt/copying/ WTFPL | |
* @author Aapo Saaristo <[email protected]> | |
*/ | |
class Warwick{protected $html;public function __construct($h){$this->go($h);}public function __toString(){return $this->html;}protected function filter($h){preg_match_all('/<(?<script>script).*?<\/script\s*>|<(?<style>style).*?<\/style\s*>|<!(?<comment>--).*?-->|<(?<tag>[\/\w.:-]*)(?:".*?"|\'.*?\'|[^\'">]+)*>|(?<text>((<[^!\/\w.:-])?[^<]*)+)|/si',$h,$m,PREG_SET_ORDER);$o=false;$r=false;$h='';foreach($m as $t){$ta=(isset($t['tag']))?strtolower($t['tag']):null;$c=$t[0];if(is_null($ta)){$s=!empty($t['script'])||!empty($t['style']);if($c=='<!-- no-minify -->'){$o=!$o;continue;}else if(!$o&&$r!='textarea')$c=preg_replace('/<!--(?!\s*(?:\[if [^\]]+]|<!|>))(?:(?!-->).)*-->/s','',$c);}else if($ta=='pre'||$ta=='textarea')$r=$ta;else if($ta=='/pre'||$ta=='/textarea')$r=false;else if($r||$o)$s=false;else{$s=true;$c=str_replace(' />','/>',preg_replace('/(\s+)(\w++(?<!\baction|\balt|\bcontent|\bsrc)="")/','$1',$c));}if($s)$c=$this->strip($c);$h.=$c;}return $h;}public function go($h){$this->html=$this->filter($h);}protected function strip($s){while(stristr($s=str_replace("\n",'',str_replace("\t",' ',str_replace("\r",'', $s))),' '))$s=str_replace(' ',' ',$s);return $s;}}function Warwick_finish($h){return new Warwick($h);}function Warwick_start(){ob_start('Warwick_finish');} | |
//add_action('get_header', 'Warwick_start'); // Uncomment to enable |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment