【问题标题】:Parse CSS file using PHP [duplicate]使用 PHP 解析 CSS 文件 [重复]
【发布时间】:2014-03-08 20:09:47
【问题描述】:

我已经使用 html dom 解析器和 ajax post 在我的本地主机中下载了 css 文件..

<?php
        require'simple_html_dom.php';
        $srcCode = $_POST['doc'];       
        $url=$_POST['Url'];             
        $url_path=$url; 
        $html = file_get_html('template/'.$name.'.html');
        if(!file_exists('template/css'))    
            {mkdir('template/css',0777, true);}     
        foreach($html->find('link') as $link)    
        {
                $linkpath=$link->href;
                $links = explode("/", $linkpath);   
                $linkName = end($links);
                file_put_contents('/template/css/'.$linkName,file_get_contents($url_path.$linkpath));   
        }
?>

现在我要使用 php 读取那些 css 文件..或者说我要获取(下载)这些 css 的所有图像 src..

background: url(../images/interface.png) no-repeat -1px -680px;
border: 0 none;
color: #534a39;
font-size: 16px;
height: 52px;
line-height: 42px;
margin: 24px auto 25px;
width: 281px;
text-indent: 40px;

如何解析css元素??如何获取css内容??请帮帮我……

【问题讨论】:

    标签: javascript php jquery html css


    【解决方案1】:

    此代码有效

    function parse($file){
        $css = file_get_contents($file);
        preg_match_all( '/(?ims)([a-z0-9\s\.\:#_\-@,]+)\{([^\}]*)\}/', $css, $arr);
        $result = array();
        foreach ($arr[0] as $i => $x){
            $selector = trim($arr[1][$i]);
            $rules = explode(';', trim($arr[2][$i]));
            $rules_arr = array();
            foreach ($rules as $strRule){
                if (!empty($strRule)){
                    $rule = explode(":", $strRule);
                    $rules_arr[trim($rule[0])] = trim($rule[1]);
                }
            }
    
            $selectors = explode(',', trim($selector));
            foreach ($selectors as $strSel){
                $result[$strSel] = $rules_arr;
            }
        }
        return $result;
    }
    $css = parse('filePath');
    

    并使用它

    $css['#selector']['color'];
    

    【讨论】:

    • 我已经获得了 css Url 标签并下载这些图像内容......
    【解决方案2】:

    你好,我写了简单的代码

     $yourRgx = '/images (\w+)/gi';
     $contentFile = file_get_contents('file.css');
    
     preg_match_all($yourRgx, $contentFile, $result);
     print_r($result);
    

    这样的逻辑:

    1- 创建您的正则表达式或文本 ("images/") 或 /images (\w+)/gi

    2- 使用@file_get_contents 打开文件

    3- 使用 php preg_match_all() 函数并搜索所有文本

    【讨论】:

      猜你喜欢
      • 2011-04-06
      • 2012-06-22
      • 2017-07-31
      • 2012-02-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多