【问题标题】:Regular expression for media queries in CSSCSS中媒体查询的正则表达式
【发布时间】:2012-12-18 05:04:30
【问题描述】:

我正在寻找一种从 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)只返回第一行(显然)

【问题讨论】:

  • 您能在ideone.comcodepad.org 上准备一个演示吗?
  • 你想要整个 css 块,还是只想要以 @media 开头的行?

标签: php regex styles media-queries


【解决方案1】:

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

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

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

【讨论】:

  • 谢谢,这可以解决问题,而且比preg_match_all快一点
猜你喜欢
  • 2016-08-22
  • 1970-01-01
  • 1970-01-01
  • 2022-01-25
  • 2019-08-20
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多