4

CSS ファイルからメディア クエリを抽出する方法を探しています。

/* "normal" css selectors

@media only screen and (max-device-width: 480px) {
    body{-webkit-text-size-adjust:auto;-ms-text-size-adjust:auto;}
    img {max-width: 100% !important; 
         height: auto !important; 
    }
}

@media only screen and (max-device-width: 320px) {
    .content{ 
        width: 320px;
    }
}

今はメディアクエリだけを取得したいと思っています。検索の開始は常に@mediaであり、検索の終了は常に中かっこであり、その後にオプションの空白と別の中かっこが続きます。

私が持っている唯一のものは

preg_match_all('#@media ?[^{]+?{XXX#',$stylesheetstring, $result);

XXX、私が探している不足している部分です。

現在のもの(Xなし)は最初の行のみを返します(明らかに)

4

1 に答える 1

9

メディア ブロック全体が必要であると仮定すると、これは正規表現の適切な仕事ではないと思います。

ただし、単純な解析関数を実装できます。

function parseMediaBlocks($css)
{
    $mediaBlocks = array();

    $start = 0;
    while (($start = strpos($css, "@media", $start)) !== false)
    {
        // stack to manage brackets
        $s = array();

        // get the first opening bracket
        $i = strpos($css, "{", $start);

        // if $i is false, then there is probably a css syntax error
        if ($i !== false)
        {
            // push bracket onto stack
            array_push($s, $css[$i]);

            // move past first bracket
            $i++;

            while (!empty($s))
            {
                // if the character is an opening bracket, push it onto the stack, otherwise pop the stack
                if ($css[$i] == "{")
                {
                    array_push($s, "{");
                }
                elseif ($css[$i] == "}")
                {
                    array_pop($s);
                }

                $i++;
            }

            // cut the media block out of the css and store
            $mediaBlocks[] = substr($css, $start, ($i + 1) - $start);

            // set the new $start to the end of the block
            $start = $i;
        }
    }

    return $mediaBlocks;
}
于 2013-01-03T19:33:22.223 に答える