【发布时间】:2016-11-13 21:21:40
【问题描述】:
我想将样式表拆分为数组,使每个选择器都与他的样式分开排列。到目前为止,我有这段代码并且运行良好,但在有媒体查询的情况下却不行。我想要实现的是,我将媒体查询中的选择器拆分为单个数组,但每个数组也都有自己的媒体查询选择器。 这是 HTML 中的样式示例
<style>
#abc{ background-color: gray; font-size: 10px;}
.abc { background-color: gray; font-size: 10px;}
@media only screen and (max-width:640px) {
#abc {
height: 200px !important;
}
}
@media only screen and (max-width:640px) {
#abcd {
height: 200px !important;
}
.abcd {
height: 200px !important;
}
}
</style>
这是我到目前为止的代码:
$dom = new DomDocument();
@$dom->loadHTML($html);
$para = $dom->getElementsByTagName('style'); #DOMNodeList
if ($para instanceof DOMNodeList) {
foreach ($para as $node) {
printf ($node->nodeValue);
}
}
$file = $node->nodeValue;
$arrs = explode('}', $file);
for ($i = 0; $i < count($arrs); $i++)
{
echo 'style ' . $i . ' - ' . $arrs[$i] . '<br />';
}
这是我得到的 uotput:
style 0 - #abc{ background-color: gray; font-size: 10px;
style 1 - .abc { background-color: gray; font-size: 10px;
style 2 - @media only screen and (max-width:640px) { #abc { height: 200px !important;
style 3 -
style 4 - @media only screen and (max-width:640px) { #abcd { height: 200px !important;
style 5 - .abcd { height: 200px !important;
想要的输出:
style 0 - #abc{ background-color: gray; font-size: 10px;
style 1 - .abc { background-color: gray; font-size: 10px;
style 2 - @media only screen and (max-width:640px) { #abc { height: 200px !important;
style 3 -
style 4 - @media only screen and (max-width:640px) { #abcd { height: 200px !important;
style 5 - @media only screen and (max-width:640px) { .abcd { height: 200px !important;
获得它的正确方法是什么?
【问题讨论】:
-
if ($para instanceof DOMNodeList) {:这个测试没用,$para始终是一个DOMNodeList实例,即使没有任何style标签。为什么使用printf ($node->nodeValue);?写echo $node->nodeValue;,没有什么要格式化的。 -
要回答您的主要问题,正确的方法是找到一个 css 解析器库:github.com/sabberworm/PHP-CSS-Parser
-
@CasimiretHippolyte ,我试过了,但是那个解析器不支持媒体查询。这仍然是一个悬而未决的问题
-
在这种情况下看看这个fork:github.com/yunosh/PHP-CSS-Parser
标签: php css arrays stylesheet