{"id":6181,"date":"2021-09-05T08:49:11","date_gmt":"2021-09-05T06:49:11","guid":{"rendered":"https:\/\/florianbrinkmann.com\/en\/?p=6181"},"modified":"2021-09-05T08:50:10","modified_gmt":"2021-09-05T06:50:10","slug":"php-css-parser","status":"publish","type":"post","link":"https:\/\/florianbrinkmann.com\/en\/php-css-parser-6181\/","title":{"rendered":"Prepend a class to CSS selectors in PHP"},"content":{"rendered":"\n
For a slider Gutenberg block, I added the option to enter custom CSS into a text field, that should only apply to that one block. Of course, the user should not need to write the selector that way, that it only applies to this specific block \u2013 that should be done in the background before rendering the frontend markup.<\/p>\n\n\n\n
To get this done, I searched for a PHP solution for PHP parsing and found the right tool with PHP CSS Parser<\/a><\/strong>.<\/p>\n\n\n\n\n\n\n\n Installation of the tool is done via composer:<\/p>\n\n\n To modify all selectors in a set of CSS rules in that way, that a unique class name is added in front, only a few lines are necessary. Lucky me, there was an example for that right there in the readme on GitHub (the CSS string exists in composer require sabberworm\/php-css-parser<\/code><\/div>Code language:<\/span> Bash<\/span> (<\/span>bash<\/span>)<\/span><\/small><\/pre>\n\n\n
$attributes['customCss']<\/code> in the following code:<\/p>\n\n\n