CSS中媒体查询的正则表达式


Regular expression for media queries in CSS

我正在寻找一种从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);

were XXX是我正在寻找的缺失部分。

当前的(没有X)只返回第一行(显然)

假设您想要整个媒体块,我认为这不是regex的正确工作。

但是,您可以实现一个简单的解析函数:
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;
}