CSS中媒体查询的正则表达式 [英] Regular expression for media queries in CSS

查看:77
本文介绍了CSS中媒体查询的正则表达式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在寻找一种从CSS文件提取媒体查询的方法.

I'm searching for a way to extract media queries from a CSS file.

/* "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,但搜索结束始终是大括号,然后是一些可选的空格和另一个大括号.

now I like to get only the media queries. I though the begin is always @media and the end of the search is always a curly bracket followed by some optional whitespace and another curly bracket.

我唯一拥有的是

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

XXX是我要搜索的缺少部分.

were XXX is the missing part I'm searching for.

当前(不带X)仅返回第一行(显然)

The current one (without the X) only returns the first line (obviously)

推荐答案

假设您需要整个媒体块,我认为这不是正则表达式的正确选择.

Assuming you want the entire media block, I don't think this is the right job for regex.

但是,您可以实现一个简单的解析功能:

You could however, implement a simple parsing function:

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;
}

这篇关于CSS中媒体查询的正则表达式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆