Search code examples
phppreg-replaceminify

Removing empty CSS Selector with PHP preg_replace


I'm trying to get a whole CSS file through compression. It works fine but I'd like to remove empty CSS selectors. This file is procedurally generated so it leaves behind some empty tags and instead of removing them all by hand:

$buffer = str_replace('#content>#columns>#article{}', '', $buffer);
$buffer = str_replace('.menuDeeper88{}', '', $buffer);

I tried to remove them like this:

$buffer = preg_replace('/\}[.*?]\{\}/', '\}', $buffer);

Which I would imagine goes like this (just a clarification):

Replace any case of '}ANY_CHARACTERS{}' with ''

But the preg_replace method didn't work. I was hoping someone here could help me make it work.

I thank you in advance.


Solution

  • Use this:

    preg_replace('/(?:[^\r\n,{}]+)(?:,(?=[^}]*{)|\s*{[\s]*})/', '', $buffer);
    

    Tested with: https://regex101.com/r/pX0wR0/3

    Regular expression modified from: What is the REGEX of a CSS selector