I have a REGEX from github which seems to work fine, however it won't handle commented lines.
$regex = '/(?:@import)(?:\\s)?(?:(?:(?:\\()(["\'])?(?:[^"\')]+)\\1(?:\\))|(["\'])(?:.+)\\2)(?:[A-Z\\s])*)+(?:;)/';
This REGEX will be tested on content like this:
$content =
'// Layout & components // this should fail
@import "variables", "mixins"; // this should validate
// @import "tools", "functions"; // this should fail
// @import "media/vendor/bootstrap/scss/root"; // this should fail
@import "media/vendor/bootstrap/scss/reboot"; // this should validate
@import "../../../media/vendor/bootstrap/scss/tools"; // this should validate
@import url("some.css"); // this should fail
// @import url("some.css"); // this should fail
//@import url("some.css"); // this should fail
// @import some; // this should fail
//@import some; // this should fail
//@import"some"; // this should fail
//@importsome; // this should fail
In the above example, the first line will be ignored because it doesn't have '@import' but the second line still passes (will not be ignored) because it's not a handled case.
I've setup a regex101 which doesn't work live, however it does work on my local environment.
What I need:
- I'm thinking I should add something like
(^\\n?!:(\/\/))
at the beginning but I don't know if that's going to work or it won't do something else. - This REGEX would work with cases like
@import url("bar.css");
I would like to remove this case, make it only work with `@import "bar.scss". - Some suggest I should strip comments before applying this REGEX, I tested this
preg_replace("/^\\/{2}.*|\\/\\*.*\\*\\/$/", '', $content)
from here but it breaks my code, so I would like to know what you think it's best.
Appreciate any reply. Thank you.
My Answer:
^\s*\/\/.*$|^\s*\/\*.*\*\/)*)?([^;]+);/';
To ignore commented lines, you can add a negative lookahead assertion to exclude lines that start with "//" or "/*":
$regex = '/(?:@import)(?:\\s)?(?:(?:(?:\\()([^;]+);)(?![^\S\r\n]*\/\/|\/\*))/';
This will match lines that contain "@import" followed by a semicolon, while ignoring lines that start with "//" or "/*".
Rate this post
5 of 5 based on 6730 votesComments