Search code examples
phpregexpcre

Regex match multiple instances


I have combined and minified multiple CSS files into one string, like this:

@import "path/to/file1";.my-class{font-size:24px;}@import "path/to/file2";

But now I want to "turn off" importing. So, I want to remove all instances of @import "something"; and get this:

.my-class{font-size:4px;}

I am currently using this:

echo preg_replace("(@import \".*\";)", "", $minified_css);

But that replaces the whole string. i.e., It's not stopping at the first instance of "; and restarting.

How do I get the regex to replace the individual @import instances?


Solution

  • You should preferable use this regex,

    @import\s+"[^"]+";
    

    And remove it with empty string

    Demo

    Also, in your regex (@import \".*\";) avoid using ( ) as you don't need to uselessly group your regex when you are replacing it with empty string. Also avoid usage of .* else it will greedily match everything possible and may give you unexpected results.

    Try this PHP code snippet,

    $minified_css = '@import "path/to/file1";.my-class{font-size:24px;}@import "path/to/file2";';
    echo preg_replace('/@import\s+\"[^"]+\";/', '', $minified_css);
    

    Prints,

    .my-class{font-size:24px;}
    

    I don't think you need to use global g modifier in preg_replace as that happens by default and you can control the replacement number by passing a third parameter. Also, you don't need to use m multiline modifier as we aren't use start/end anchors in our pattern.

    PHP code demo