用 PHP 解析 CSS 文件 [英] Parse a CSS file with PHP

查看:35
本文介绍了用 PHP 解析 CSS 文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想用 PHP 解析(以一种特殊的方式)一个 CSS 文件.

I want to parse (in a special way) a CSS file with PHP.

示例:

cssfile.css:

#stuff {
    background-color: red;
}

#content.postclass-subcontent {
    background-color: red;
}

#content2.postclass-subcontent2 {
    background-color: red;
}

而且我希望 PHP 返回每个名称中包含 postclass 的类名.

And I want that PHP returns me each class name that have the postclass in its name.

结果看起来像这个例子中的一个数组:

The result look like an array having in this example:

arrayentry1:
#content.postclass-subcontent
arrayentry2:
#content2.postclass-subcontent2

但我更擅长正则表达式.以某种方式搜索postclass"然后抓取孔线并放入数组中.

But I'm worse at regular expressions. somehow search for "postclass" and then grap the hole line and put into an array.

谢谢你,我用它来解析一个类似于 confic 文件的 css 文件.

thank you and i used it to parse a css file simliar to a confic file.

$(function () {
    $.get('main.css', function (data) {
        data = data.match(/(#[a-z0-9]*? .?postclass.*?)s?{/g);
        if (data) {
            $.each(data, function (index, value) {
                value = value.substring(0, value.length - 2);
                $(value.split(' .')[0]).wrapInner('<div class="' + value.split('.')[1] + '" />');
            });
        }
    });
});

是我的最终代码.所以我可以在不编辑布局的情况下轻松地将 div 包裹在一些 hardcode-html 周围.所以我只需要编辑我的 cssfile 并在那里添加类似

was my final code. so i can wrap easily a div around some hardcode-html without editing the layout. so i just have to edit my cssfile and add there something like

并且我的代码搜索 id 并用 div 包装内部内容.当我只需要在某物周围添加一个 div 以获得清晰或背景时,我需要它来进行快速修复.

and my code searchs for the id and wraps the inner content with an div. i needed that for quickfixes when i just have to add a div around something for a clear or a background.

推荐答案

这是一个使用正则表达式的快速而肮脏的独立黑客:

Here is a quick and dirty standalone hack using regex:

$input = '
#stuff {
    background-color: red;
}

#content.postclass-subcontent {
    background-color: red;
}

#content2.postclass-subcontent2 {
    background-color: red;
}
';

$cssClassName = 'postclass';
preg_match_all('/(#[a-z0-9]*?.?'.addcslashes($cssClassName, '-').'.*?)s?{/', $input, $matches);
var_dump($matches[1]);

结果:

array(2) {
  [0]=>
  string(29) "#content.postclass-subcontent"
  [1]=>
  string(31) "#content2.postclass-subcontent2"
}

这篇关于用 PHP 解析 CSS 文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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