[英]Regex match multiple instances
I have combined and minified multiple CSS files into one string, like this: 我将多个CSS文件合并并缩小为一个字符串,如下所示:
@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";
因此,我想删除
@import "something";
所有实例@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. 但这将替换整个字符串。 ie, It's not stopping at the first instance of
";
and restarting. 即,它不会在
";
的第一个实例处停止并重新启动。
How do I get the regex to replace the individual @import
instances? 如何获取正则表达式来替换单个
@import
实例?
You should preferable use this regex, 您最好使用此正则表达式,
@import\s+"[^"]+";
And remove it with empty string 并用空字符串将其删除
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. 另外,在您的正则表达式
(@import \\".*\\";)
避免使用(
)
因为在用空字符串替换正则表达式时,您不需要无用地分组。 Also avoid usage of .*
else it will greedily match everything possible and may give you unexpected results. 还要避免使用
.*
否则它将贪婪地匹配所有可能的内容,并可能给您带来意想不到的结果。
Try this PHP code snippet, 试试这个PHP程式码片段,
$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. 我认为您不需要在
preg_replace
使用全局g
修饰符,因为默认情况下会发生这种情况,您可以通过传递第三个参数来控制替换编号。 Also, you don't need to use m
multiline modifier as we aren't use start/end anchors in our pattern. 另外,您不需要使用
m
多行修饰符,因为我们不在模式中使用开始/结束锚点。
You are using the greedy *
operator, which tries to match as much as possible. 您正在使用贪婪
*
运算符,该运算符尝试尽可能匹配。
Try using .*?
尝试使用
.*?
(the lazy operator) instead of .*
. (惰性运算符)而不是
.*
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.