sabberworm/php-css-parser
Parse and manipulate CSS in PHP with a fast, flexible parser. Convert CSS into an object model, inspect and edit rules, selectors, and declarations, then render back to CSS. Useful for minifying, rewriting assets, or building CSS tooling.
Install via Composer:
composer require sabberworm/php-css-parser
Start by parsing a CSS string or file:
use Sabberworm\CSS\Parser;
$parser = new Parser($cssString);
$cssDocument = $parser->parse();
The parsed $cssDocument is an object tree: CSSDocument → RuleSets (e.g., RuleSet, AtRule) → Rules → Values.
First common use case: extract and inspect selectors/rules — e.g., find all font-size declarations across a stylesheet.
$ruleSet = new RuleSet();
$ruleSet->addRule(new Rule('color', new Color('red')));
$mediaQuery = new AtRule('media', 'screen and (min-width: 768px)');
$mediaQuery->getRuleSets()->addRuleSet($ruleSet);
$cssDocument->addRuleSet($mediaQuery);
echo $cssDocument->render(); // minify via ->render(new OutputFormat())
Sabberworm\CSS\Parser\Exception\ParserException — wrap parse() in try/catch for robustness.div {}) are preserved — filter them manually if needed (getRuleSets() → getRules()).-webkit-box) may parse inconsistently — always validate AST structure before modification.calc(), var(--custom)) are represented as CSSString or Value objects — avoid naive string concatenation.OutputFormat to control minification (e.g., preserve line breaks for debugging).How can I help you explore Laravel packages today?