Home >Backend Development >PHP Tutorial >How to Extract Class Names Containing \'postclass\' from a CSS File with PHP?
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(":", $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!