Skip to content

Instantly share code, notes, and snippets.

@nasrulhazim
Created February 25, 2018 12:29
Show Gist options
  • Save nasrulhazim/740bdf1175c0ad85be1864c27304aa61 to your computer and use it in GitHub Desktop.
Save nasrulhazim/740bdf1175c0ad85be1864c27304aa61 to your computer and use it in GitHub Desktop.
Minify HTML
<?php
namespace App\Http\Middleware;
use Closure;
class MinifyHtml
{
/**
* Handle an incoming request.
*
* @param \Illuminate\Http\Request $request
* @param \Closure $next
*
* @return mixed
*/
public function handle($request, Closure $next)
{
$response = $next($request);
return $this->html($response);
}
public function html($response)
{
$buffer = $response->getContent();
$replace = [
'/<!--[^\[](.*?)[^\]]-->/s' => '',
"/<\?php/" => '<?php ',
"/\n([\S])/" => '$1',
"/\r/" => '',
"/\n/" => '',
"/\t/" => '',
'/ +/' => ' ',
];
if (false !== strpos($buffer, '<pre>')) {
$replace = [
'/<!--[^\[](.*?)[^\]]-->/s' => '',
"/<\?php/" => '<?php ',
"/\r/" => '',
"/>\n</" => '><',
"/>\s+\n</" => '><',
"/>\n\s+</" => '><',
];
}
$buffer = preg_replace(array_keys($replace), array_values($replace), $buffer);
$response->setContent($buffer);
return $response;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment