Home  >  Article  >  Backend Development  >  How to Extract Class Names Containing \"postclass\" from a CSS File with PHP?

How to Extract Class Names Containing \"postclass\" from a CSS File with PHP?

Linda Hamilton
Linda HamiltonOriginal
2024-10-29 21:40:02747browse

How to Extract Class Names Containing

Utilize PHP to Parse CSS Files

Question: How can I effectively parse a CSS file using PHP, specifically extracting class names containing "postclass"?

In CSS:

#stuff {
    background-color: red;
}

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

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

The desired PHP output:

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

Answer:

<code class="php">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(&quot;:&quot;, $strRule);
                $rules_arr[trim($rule[0])] = trim($rule[1]);
            }
        }
        
        $selectors = explode(',', trim($selector));
        foreach ($selectors as $strSel){
            $result[$strSel] = $rules_arr;
        }
    }
    return $result;
}</code>

You can then use it as follows:

<code class="php">$css = parse('css/'.$user['blog'].'.php');
$css['#selector']['color'];</code>

The above is the detailed content of How to Extract Class Names Containing \"postclass\" from a CSS File with PHP?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn