Rumah > Artikel > hujung hadapan web > Bagaimana untuk Mengekstrak Kelas yang Mengandungi "kelas pos" daripada Fail CSS dengan PHP?
Question:
You seek a method to parse a CSS file in PHP and extract each class name containing "postclass" in its name. The desired output is an array of these class names.
Solution:
Using Regular Expressions:
The following PHP function accomplishes the task using regular expressions:
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]); if (strpos($selector, 'postclass') !== false) { $result[] = $selector; } } return $result; }
Usage:
$css = parse('css/'.$user['blog'].'.php'); print_r($css); // Output: ["#content.postclass-subcontent", "#content2.postclass-subcontent2"]
This function parses the CSS file and stores the matching class names in the $result array. It then returns the array.
Using Ajax and jQuery:
An alternative approach uses Ajax and jQuery to fetch the CSS file and extract the required classes:
$(function () { $.get('main.css', function (data) { data = data.match(/(#[a-z0-9]*?\ .?postclass.*?)\s?\{/g); if (data) { $.each(data, function (index, value) { value = value.substring(0, value.length - 2); $(value.split(' .')[0]).wrapInner('<div class="' + value.split('.')[1] + '" />'); }); } }); });
This code fetches the CSS file, extracts the class names containing "postclass," and wraps matching elements with a DIV based on the CSS class.
Atas ialah kandungan terperinci Bagaimana untuk Mengekstrak Kelas yang Mengandungi "kelas pos" daripada Fail CSS dengan PHP?. Untuk maklumat lanjut, sila ikut artikel berkaitan lain di laman web China PHP!