4

I'm trying to remove include statements from a css file. So given a css file like

@import url("css1.css");
@import url("css2.css");
@import url("css3.css");
.myfirstclass {color:red}

after I run the command I want to be

.myfirstclass {color:red}

This is the command I am using but it isn't working. Is there a way to do this?

$css_file = preg_replace("/^@import url(.*)$/", "", $css_file);    
5
  • Is every import in the css file terminated with a linebreak of some sort? Meaning, its not a .min'ified .css file? Commented Feb 10, 2018 at 14:34
  • The parentheses need \escaping else they are a capture group Commented Feb 10, 2018 at 14:35
  • Also, there might be whitespace before the @, and dont forget the semicolon... I'm not a wiz with regex patterns, so it would take me way too long to figure it out when i know a regexpert will pop in and solve this riddle in a flash! :) Commented Feb 10, 2018 at 14:37
  • 1
    You forgot m modifier $css_file = preg_replace("/^\s*@import url.*/m", "", $css_file); Commented Feb 10, 2018 at 14:37
  • @AlexK The unescaped parentheses does not make the pattern fail, it just makes the pattern less literal. It would effectively just create a capture group which contains the substring from ( to ;. The faulty component is the $. Either add the m flag or remove the $. Or best, use revo's second method. Commented Feb 12, 2018 at 1:20

1 Answer 1

2

Caret ^ alongside dollar sign $ mean asserting start of input string and end of it respectively unless m flag is set. You also need to check for spaces in beginning of line and match linebreaks at end:

$css_file = preg_replace("/^\s*@import url.*\R*/m", "", $css_file);  
                             ^               ^  ^

In case of working with minified CSS:

$css_file = preg_replace("/@import[^;]+;/", "", $css_file);  
Sign up to request clarification or add additional context in comments.

2 Comments

Thank you. This worked great. But please explain what the R is for. I can't find it mentioned in my searches for it. From your text, it seems it might refer to the line break but examples I found sayo to use \r\n.
\R means any kind of linebreaks which includes Unicode linebreaks as well.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.