douwen9540 2016-10-05 18:31
浏览 187
已采纳

php获取css文件中的所有类名

Let's say I have a css file as shown...

span {
    //whatever
}

.block {
    //whatever
}

.block, .something {
    //whatever
}

.more,
h1,
h2 {
    //whatever
}

I want to extract all class names and put it into an array, but I want to keep the structure, so the array will look like...

["span", ".block", ".block, .something", ".more, h1, h2"]

So there are four items.

This is my attempt...

$homepage = file_get_contents("style.css");

//remove everything between brackets (this works)
$pattern_one = '/(?<=\{)(.*?)(?=\})/s';

//this regex does not work properly
$pattern_two = "/\.([\w]*)\s*{/";

$stripped = preg_replace($pattern_one, '', $homepage);
$selectors = array();
$matches = preg_match_all($pattern_two, $stripped, $selectors);

what is the proper regex to use for pattern 2?

  • 写回答

1条回答 默认 最新

  • douhua1760 2016-10-05 18:46
    关注

    Like this?

    <?php
    $css = "span {
        //whatever
    }
    
    .block {
        //whatever
    }
    
    .block, .something {
        //whatever
    }
    
    .more,
    h1,
    h2 {
        //whatever
    }";
    
    $rules = [];
    
    $css = str_replace("", "", $css); // get rid of new lines
    $css = str_replace("
    ", "", $css); // get rid of new lines
    
    // explode() on close curly braces
    // We should be left with stuff like:
    //   span{//whatever
    //   .block{//whatever
    $first = explode('}', $css);
    
    // If a } didn't exist then we probably don't have a valid CSS file
    if($first)
    {
        // Loop each item
        foreach($first as $v)
        {
            // explode() on the opening curly brace and the ZERO index should be the class declaration or w/e
            $second = explode('{', $v);
    
            // The final item in $first is going to be empty so we should ignore it
            if(isset($second[0]) && $second[0] !== '')
            {
                $rules[] = trim($second[0]);
            }
        }
    }
    
    // Enjoy the fruit of PHP's labor :-)
    print_r($rules);
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥60 版本过低apk如何修改可以兼容新的安卓系统
  • ¥25 由IPR导致的DRIVER_POWER_STATE_FAILURE蓝屏
  • ¥50 有数据,怎么建立模型求影响全要素生产率的因素
  • ¥50 有数据,怎么用matlab求全要素生产率
  • ¥15 TI的insta-spin例程
  • ¥15 完成下列问题完成下列问题
  • ¥15 C#算法问题, 不知道怎么处理这个数据的转换
  • ¥15 YoloV5 第三方库的版本对照问题
  • ¥15 请完成下列相关问题!
  • ¥15 drone 推送镜像时候 purge: true 推送完毕后没有删除对应的镜像,手动拷贝到服务器执行结果正确在样才能让指令自动执行成功删除对应镜像,如何解决?