Written by Manabu Bannai

PHPが吐き出すHTMLファイルを『自動的に最小化する』スクリプト

PHP PROGRAMMING


PHPが吐き出すHTMLファイルを『自動的に最小化する』スクリプトです。

<?php
function sanitize_output($buffer) {
	$search = array(
		'/\>[^\S ]+/s',  // strip whitespaces after tags, except space
		'/[^\S ]+\</s',  // strip whitespaces before tags, except space
		'/(\s)+/s'       // shorten multiple whitespace sequences
	);
	$replace = array(
		'>',
		'<',
		'\\1'
	);
	$buffer = preg_replace($search, $replace, $buffer);
	return $buffer;
}
ob_start("sanitize_output");
?>

具体例

下記の感じです。header.phpとかが最初に読み込まれるはずなので、そこに記載しましょう。

<?php
function sanitize_output($buffer) {
	$search = array(
		'/\>[^\S ]+/s',  // strip whitespaces after tags, except space
		'/[^\S ]+\</s',  // strip whitespaces before tags, except space
		'/(\s)+/s'       // shorten multiple whitespace sequences
	);
	$replace = array(
		'>',
		'<',
		'\\1'
	);
	$buffer = preg_replace($search, $replace, $buffer);
	return $buffer;
}
ob_start("sanitize_output");
?><!DOCTYPE html>
<html>
<head>
	<title>タイトル</title>
</head>
<body>
	<h1>PHPが吐き出すHTMLファイルを『自動的に最小化する』スクリプト</h1>
	<p>ここにテキストが入ります。ここにテキストが入ります。ここにテキストが入ります。ここにテキストが入ります。ここにテキストが入ります。ここにテキストが入ります。ここにテキストが入ります。</p>
</body>
</html>

以上、備忘録的なメモでした。