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

Linda Hamilton
Release: 2024-10-29 21:40:02
Original
746 people have browsed it

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;
}
Copy after login

The desired PHP output:

arrayentry1:
#content.postclass-subcontent
arrayentry2:
#content2.postclass-subcontent2
Copy after login

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>
Copy after login

You can then use it as follows:

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

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!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!