Let's say I have a css file as shown...
假设我有一个css文件,如下所示……
span {
//whatever
}
.block {
//whatever
}
.block, .something {
//whatever
}
.more,
h1,
h2 {
//whatever
}
I want to extract all class names and put it into an array, but I want to keep the structure, so the array will look like...
我想提取所有的类名并将其放入一个数组中,但是我想保留这个结构,这样数组看起来就像…
["span", ".block", ".block, .something", ".more, h1, h2"]
So there are four items.
有四项。
This is my attempt...
这是我尝试…
$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);
what is the proper regex to use for pattern 2?
用于模式2的适当regex是什么?
1 个解决方案
#1
3
Like this?
像这样的吗?
<?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);
#1
3
Like this?
像这样的吗?
<?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);