Esta função explica como minimificar códigos HTML usando PHP. Vale a pena dar uma debugada para entender o funcionamento e customizar para suas necessidad function compressHtml($buffer) { // Iniciando variáveis para busca de tags $foundTxt =...

Esta função explica como minimificar códigos HTML usando PHP. Vale a pena dar uma debugada para entender o funcionamento e customizar para suas necessidad function compressHtml($buffer) { // Iniciando variáveis para busca de tags $foundTxt = null; $foundPre = null; $foundCode = null; $foundScript = null; // Procurando tags textarea, pre, code e script preg_match_all('#\<textarea.*\>.*\<\/textarea\>#Uis', $buffer, $foundTxt); preg_match_all('#\ <pre.*\>.*\<\/pre\>#Uis', $buffer, $foundPre); preg_match_all('#\<code.*\>.*\<\/code\>#Uis', $buffer, $foundCode); preg_match_all('#\<script.*\>.*\<\/script\>#Uis', $buffer, $foundScript); // Substitui o canteúdo da tags por uma palavra chave, assim // o conteúdo pode ser posto novamente intacto no lugar. // Exemplo: $index /
$index
$buffer = str_replace($foundTxt[0], array_map(function($el){ return ''.$el.''; }, array_keys($foundTxt[0])), $buffer); $buffer = str_replace($foundPre[0], array_map(function($el){ return '
'.$el.'
'; }, array_keys($foundPre[0])), $buffer); $buffer = str_replace($foundCode[0], array_map(function($el){ return ''.$el.''; }, array_keys($foundCode[0])), $buffer); $buffer = str_replace($foundScript[0], array_map(function($el){ return '// '; }, array_keys($foundScript[0])), $buffer); // Minifica o html $search = array( '/\>[^\S ]+/s', // Limpando espaços em branco antes das tags '/[^\S ]+\/', // Eetirando comentários do HTML '#(?://)?<!\[CDATA\[(.*?)(?://)?\]\]>#s' // Deixando CDATA em linhas separadas ); $replace = array( '>', '<', '\\1', '', "//" ); $buffer = preg_replace($search, $replace, $buffer); // Replacing back with content $buffer = str_replace(array_map(function($el){ return ''.$el.''; }, array_keys($foundTxt[0])), $foundTxt[0], $buffer); $buffer = str_replace(array_map(function($el){ return '
'.$el.'
'; }, array_keys($foundPre[0])), $foundPre[0], $buffer); $buffer = str_replace(array_map(function($el){ return ''.$el.''; }, array_keys($foundCode[0])), $foundCode[0], $buffer); $buffer = str_replace(array_map(function($el){ return '// '; }, array_keys($foundScript[0])), $foundScript[0], $buffer); return $buffer; }
Seja Membro Gratuítamente

Assine a newsletter para receber em seu email as publicações atualizadas neste blog

Top