CSS Minify & Beautify — PHP source
Minify CSS (strip comments and whitespace, shorten hexes and decimals) or beautify it back to readable one-declaration-per-line form. Strings stay intact. Runs locally with a shareable link.
This is the PHP implementation — the same logic the interactive tool runs, in a shareable, citable form.
<?php
// css-minify — CSS minifier & beautifier. PHP port (canonical TS:
// src/lib/css-minify.ts; Go twin: cli/css-minify). One scanner masks string
// literals as "\x00n\x00" sentinels and drops /* */ comments; every textual
// rule then runs on the masked text with PCRE patterns carrying no
// lookaround (backreferences are PCRE-supported) so the Go twin reproduces
// byte-identical output. minify — collapse whitespace, strip spaces around
// {} ; : , > (sibling + and ~ combinators keep theirs), drop the last
// semicolon before }, lowercase hexes, shorten #aabbcc → #abc (never
// 8-digit alpha), strip leading zeros (0.5 → .5) and trailing fraction
// zeros (1.50 → 1.5, 1.00 → 1, .00 → 0). beautify — one selector per
// block, one declaration per line at 2-space depth, each declaration
// keeping its own semicolon. Errors travel in result["error"] (null =
// success); empty input is a successful empty output, never an error.
/** Scan CSS into ['masked', 'strings']; mask every string literal as a
* "\x00n\x00" sentinel and drop block comments. On failure the array has
* only an "error" key carrying the pinned TS string. */
function css_minify_mask(string $raw): array
{
$out = '';
$strings = [];
$i = 0;
$n = strlen($raw);
while ($i < $n) {
$ch = $raw[$i];
if ($ch === '"' || $ch === "'") {
$start = $i;
$i++;
while ($i < $n && $raw[$i] !== $ch) {
if ($raw[$i] === '\\' && $i + 1 < $n) $i++; // escaped char
$i++;
}
if ($i >= $n) return ['error' => 'Unterminated string'];
$i++;
$strings[] = substr($raw, $start, $i - $start);
$out .= "\x00" . (count($strings) - 1) . "\x00";
} elseif ($ch === '/' && $i + 1 < $n && $raw[$i + 1] === '*') {
$end = strpos($raw, '*/', $i + 2);
if ($end === false) return ['error' => 'Unterminated comment'];
$i = $end + 2;
} else {
$out .= $ch;
$i++;
}
}
return ['masked' => $out, 'strings' => $strings];
}
function css_minify_unmask(string $text, array $strings): string
{
return preg_replace_callback('/\x00(\d+)\x00/', fn($m) => $strings[(int) $m[1]], $text);
}
/** Conservative minification — see the header for the exact rule list. */
function css_minify_minify(string $raw): array
{
$text = trim($raw);
if ($text === '') return ['output' => '', 'error' => null];
$m = css_minify_mask($text);
if (isset($m['error'])) return ['output' => '', 'error' => $m['error']];
$css = $m['masked'];
$css = preg_replace('~\s+~', ' ', $css);
$css = preg_replace('~\s*([{};:,>])\s*~', '$1', $css);
$css = preg_replace('~;+}~', '}', $css);
$css = trim($css);
$css = preg_replace_callback('~#[0-9a-fA-F]{3,8}~', fn($h) => strtolower($h[0]), $css);
$css = preg_replace('~#([0-9a-f])\1([0-9a-f])\2([0-9a-f])\3([^0-9a-f]|$)~', '#$1$2$3$4', $css);
$css = preg_replace('~(^|[^A-Za-z0-9_.#$%-])0+(\.[0-9]+)~', '$1$2', $css);
$css = preg_replace('~(\.[0-9]*[1-9])0+([^0-9]|$)~', '$1$2', $css);
$css = preg_replace('~(^|[^A-Za-z0-9_.#$%-])([0-9]+)\.0+([^0-9]|$)~', '$1$2$3', $css);
// '${1}0' (not '$10'): group 1 + a literal '0', unambiguous.
$css = preg_replace('~(^|[^A-Za-z0-9_.#$%-])\.0+([^0-9]|$)~', '${1}0$2', $css);
return ['output' => css_minify_unmask($css, $m['strings']), 'error' => null];
}
/** Structural beautifier — 2-space indentation, declarations one per line. */
function css_minify_beautify(string $raw): array
{
$text = trim($raw);
if ($text === '') return ['output' => '', 'error' => null];
$m = css_minify_mask($text);
if (isset($m['error'])) return ['output' => '', 'error' => $m['error']];
$css = preg_replace('~\s+~', ' ', $m['masked']);
$strings = $m['strings'];
$out = '';
$buffer = '';
$depth = 0;
$flush = function (bool $semi) use (&$out, &$buffer, &$depth): void {
$decl = trim($buffer, ' \t\n\r\v');
if ($decl !== '') $out .= str_repeat(' ', $depth) . $decl . ($semi ? ';' : '') . "\n";
$buffer = '';
};
$n = strlen($css);
for ($i = 0; $i < $n; $i++) {
$ch = $css[$i];
if ($ch === '{') {
$sel = trim($buffer, ' \t\n\r\v');
$buffer = '';
if ($sel === '') return ['output' => '', 'error' => 'Block without a selector'];
$out .= str_repeat(' ', $depth) . $sel . " {\n";
$depth++;
} elseif ($ch === '}') {
$flush(false);
$depth--;
if ($depth < 0) return ['output' => '', 'error' => 'Unbalanced }'];
$out .= str_repeat(' ', $depth) . "}\n";
} elseif ($ch === ';') {
$flush(true);
} else {
$buffer .= $ch;
}
}
if ($depth !== 0) return ['output' => '', 'error' => 'Unclosed block'];
$flush(false);
return ['output' => css_minify_unmask($out, $strings), 'error' => null];
}
// Example:
// css_minify_minify("body { color : #AABBCC; margin : 0.50px; }")["output"]
// → 'body{color:#abc;margin:.5px}'
// css_minify_beautify("a{b:c}")["output"] → "a {\n b: c;\n}\n"
Also available in 13 other languages
Every CosmoDev tool ships its pure logic in TypeScript (web) and Go (CLI), with authored implementations in a dozen-plus languages — the same contract, ported. Compare all languages side by side →