我想将样式表拆分成数组,这样每个选择器都在与他的样式分开的数组中。到目前为止,我有这段代码并且运行良好,但在有媒体查询的情况下却不行。我想要实现的是,我将媒体查询中的选择器拆分为单个数组,但每个数组也都有自己的媒体查询选择器。 这是 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;
获得它的正确方法是什么?
最佳答案
您可以尝试这样的事情,请记住,这个答案要求您知道或确保媒体查询是样式表的最后一部分,并且在一种媒体和另一种媒体之间没有声明其他样式,遵循你的例子的格式。然后你可以这样做:
...
$file = $node->nodeValue;
$parts = explode('@media', $file);
// The first part of the stylesheet, where there are no media queries
$styleCount = 0;
$arrs = explode('}', $parts[0]);
for ($i = 0; $i < count($arrs); $i++)
{
echo 'style ' . $i . ' - ' . $arrs[$i] . '<br />';
$styleCount++;
}
// The media queries, remember to validate that there exists at least one before
for ($i = 1; $i < count($parts); $i++){
$arrs = explode('{', $parts[$i], 2);
$title = "@media " . $arrs[0];
$arrIn = explode('}', $arrs[1]);
for($j = 0; $j < count($arrIn); $j++){
// Validate for an empty space or a new line, it could be just something like strlen($arrIn[$j]) > 3
if(strlen($arrIn[$j]) > 4){
echo 'style ' . $styleCount . ' - ' . $title . " { " . $arrIn[$j] . '</br>';
$styleCount++;
}
}
}
关于PHP - 将样式表拆分为数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40578959/