使用 PHP 向 CSS 摘录中的所有选择器添加前缀?
好吧,假设我有一个包含一些 CSS 代码的变量 $css
。我想要做的是在每个选择器前面添加特定的文本。例如,以下代码:
#hello, .class{width:1px;height:1px;background-color:#AAA;}
div{font-size:1px}
input, a, span{padding:4px}
将转换为:
#someId #hello, #someId .class{ ... }
#someId div{ ... }
#someId input, #someId a, #someId span{ ... }
我一直在尝试使用多个 explode()
。然而,我一直没能有效地完成任务。有什么想法吗?
谢谢! JCOC611
Ok so lets say I have a variable $css
that contains some CSS code. What I want to do is to add a certain text in front of each selector. So for example, the following code:
#hello, .class{width:1px;height:1px;background-color:#AAA;}
div{font-size:1px}
input, a, span{padding:4px}
Would be converted into:
#someId #hello, #someId .class{ ... }
#someId div{ ... }
#someId input, #someId a, #someId span{ ... }
I have been trying to use several explode()
s. However, I haven't been able to accomplish the task effectively. Any thoughts?
Thanks! JCOC611
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
根据乔恩的建议,我编写了以下代码:
要查看它的工作原理,请参阅 http://codepad.org/bqRd83gu
Based on Jon's suggestion I wrote the following code:
To see that it works see http://codepad.org/bqRd83gu
我写了改进版本,因为我还需要媒体查询。这是我基于 Jan 的答案的函数:
它适用于媒体查询和@font-face。
I wrote improved version because I also need media query. This is my function based on Jan's answer:
It works with media query and also @font-face.
这是更高级的 JohnyFree 变体,几乎没有什么
脏
修改。这个变体将整个 css 打包到一行中,
也删除所有 css 注释,并检查
$partDetails[1]
是否确实在最后设置,然后内爆 *(lastelse
)给 JohnyFree 更多声誉伙计们,他应得的。
ps:我在我修改过的地方添加了
# shell style comments
。This is more advanced JohnyFree's variant, with few
dirty
modifications.This variant packs whole css into a single line,
removes all css comments as well, and checks if
$partDetails[1]
is actually isset at the end, and than goes the imploding *(lastelse
)Give JohnyFree more reputation folks, he deserves it.
ps: I have added
# shell style comments
on places where modifications were performed by me.看起来您需要一个合适的 CSS 解析器才能知道每个选择器的开始位置。
但是,通过考虑
}
表示每个选择器的结束,并在每次出现右大括号(最后一个除外)之后插入必要的文本,您可能能够摆脱快速而肮脏的解决方案。It looks like you need a proper CSS parser in order to be able to tell where is the start of each selector.
However, you might be able to get away with a quick and dirty solution by considering that
}
signals the end of each selector, and inserting the necessary text after each occurrence of the closing brace except the last one.此方法将为所有选择器添加前缀。
This method will add prefixes to all selectors.
感谢各位的解决方案。
我唯一缺少的是关键帧支持。
这是我的补充:
Thanks for solution guys.
The only thing that was missing for me was keyframes support.
Here is my addition for it: