gpt4 book ai didi

php获取css文件中的所有类名

转载 作者:行者123 更新时间:2023-12-02 20:56:57 24 4
gpt4 key购买 nike

假设我有一个 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);

关于php获取css文件中的所有类名,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39881319/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com