CSS rule shortening

Definition: <?php // CSSRuleShortener.php class CSSRuleShortener { private $rules = [ 'posr' => 'position: relative', 'posa' => 'position: absolute', 'posf' => 'position: fixed', 'dsb' => 'display: block', 'dsib' => 'display: inline-block', 'dsg' => 'display: grid', 'dsf' => 'display: flex', 'marl' => 'margin-left', 'marr' => 'margin-right', 'mart' => 'margin-top', 'marb' => 'margin-bottom', 'mar' => 'margin', 'padl' => 'padding-left', 'padr' => 'padding-right', 'padt' => 'padding-top', 'padb' => 'padding-bottom', 'pad' => 'padding', 'w' => 'width', 'h' => 'height', 'bd' => 'border', 'bdl' => 'border-left', 'bdr' => 'border-right', 'bdt' => 'border-top', 'bdb' => 'border-bottom', 'bd1x' => 'border: 1px solid black' ]; private $units = [ 'x' => 'px', 'm' => 'em', 'rm' => 'rem', 'p' => '%', 'fr' => 'fr', 'vw' => 'vw', 'vh' => 'vh', ]; public function expand_all($style) { $css = []; $lines = explode(PHP_EOL, $style); for($i = 0, $len = count($lines); $i < $len; $i++) { $line = $lines[$i]; if(strpos($line, '{') > -1 || strpos($line, '}') > -1 || !strlen(trim($line))) { $css[] = $line; continue; } $exp = ''; if(preg_match('/(\d+[\.\d+]*)/', $line, $matches)) { $val = $matches[0]; list($rule, $unit) = explode($val, $line); list($repl_rule, $repl_unit) = [$this->rules[trim($rule)], $this->units[trim($unit)]]; $rule = trim($rule); $exp = "{$repl_rule}: {$val}{$repl_unit};"; } else { // Expand immediately if line is not empty $rule = trim($line); $exp = $this->rules[$rule].';'; } $css[] = "\t".$exp; } return implode(PHP_EOL, $css); } } ?> Usage: <?php require 'CSSRuleShortener.php'; $shortener = new CSSRuleShortener(); $html = <<< HTML <ul class="book"> <li class="page">page 1</li> <li class="page">page 2</li> <li class="page">page 3</li> <li class="page">page 4</li> </ul> HTML; $styles = <<< CSS .book { posr w230x h115x bdb1x padb0.2m } .page { posa bd1x pad10x mart10x } CSS; $styles = $shortener->expand_all($styles); echo <<< DOC <!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8" /> <title>CSS rule shortener</title> <style>\n{$styles}\n</style> </head> <body>\n{$html}\n</body> </html> DOC; ?> Output: <!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8" /> <title>CSS rule shortener</title> <style> .book { position: relative; width: 230px; height: 115px; border-bottom: 1px; padding-bottom: 0.2em; } .page { position: absolute; border: 1px; padding: 10px; margin-top: 10px; } </style> </head> <body> <ul class="book"> <li class="page">page 1</li> <li class="page">page 2</li> <li class="page">page 3</li> <li class="page">page 4</li> </ul> </body> </html>

If you wish, you could expand this idea to include your own rules and attempt to simplify your development process.