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

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?

假设我有一个如图所示的css文件... p>

  span {
 //whatever
}

.block {
 //whatever
}

.block,.something {
 // whatever what n} 
 
。 更多,
h1,
h2 {
 //无论什么
} 
  code>  pre> 
 
 

我想提取所有类名并将其放入数组中,但我想要 保持结构,所以数组看起来像...... p>

  [“span”,“。block”,“。block,.something”,“。more,  h1,h2“] 
  code>  pre> 
 
 

所以有四个项目。 p>

这是我的尝试...... p>

  $ homepage = file_get_contents(“style.css”); 
 
 //删除括号之间的所有内容(这可行)
 $ pattern_one ='/(?&lt; = \ {  )(。*?)(?= \})/ s'; 
 
 //这个正则表达式无法正常工作
 $ pattern_two =“/\。([\\ w] *)\ s * {/”  ; 
 
 $ stripped = preg_replace($ pattern_one,'',$ homepage); 
 $ selectors = array(); 
 $ matches = preg_match_all($ pattern_two,$ stripped,$ selectors); 
  代码>  pre> 
 
 

用于模式2的​​正确正则表达式是什么? p> div>

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