[英]How to find all class names or ids from a CSS file that contains a background image using Regular expression and PHP?
[英]php to get all class names in css file
假设我有一个如图所示的css文件...
span {
//whatever
}
.block {
//whatever
}
.block, .something {
//whatever
}
.more,
h1,
h2 {
//whatever
}
我想提取所有类名并将其放入数组中,但我想保留结构,因此数组看起来像...
["span", ".block", ".block, .something", ".more, h1, h2"]
因此,有四个项目。
这是我的尝试
$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);
模式2适用的正则表达式是什么?
像这样?
<?php
$css = "span {
//whatever
}
.block {
//whatever
}
.block, .something {
//whatever
}
.more,
h1,
h2 {
//whatever
}";
$rules = [];
$css = str_replace("\r", "", $css); // get rid of new lines
$css = str_replace("\n", "", $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);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.