php - 使用 php 从源代码中提取 css 类和 ID

标签 php css regex parsing

我原以为这会很简单,但我已经为此苦苦挣扎了一段时间。我知道那里有 CSS 解析器类可以实现我想做的事情……但我不需要它们所具有的 95% 的功能,所以它们并不真正可行,而且太重了。

我需要做的就是通过正则表达式提取 CSS 文件中使用的任何类和/或 ID 名称。这是我认为可以工作的正则表达式,但没有。

[^a-z0-9][\w]*(?=\s)

当针对我的样本运行时:

.stuffclass {
 color:#fff;
 background:url('blah.jpg');
}
.newclass{
 color:#fff;
 background:url('blah.jpg');
}
.oldclass {
 color:#fff;
 background:url('blah.jpg');
}
#blah.newclass {
 color:#fff;
 background:url('blah.jpg');
}
.oldclass#blah{
 color:#fff;
 background:url('blah.jpg');
}
.oldclass #blah {
 color:#fff;
 background:url('blah.jpg');
}
.oldclass .newclass {
 text-shadow:1px 1px 0 #fff;
 color:#fff;
 background:url('blah.jpg');
}
.oldclass:hover{
 color:#fff;
 background:url('blah.jpg');
}
.newclass:active {
 text-shadow:1px 1px 0 #000;
}

它确实匹配了我想要的大部分,但它还包括大括号并且与 ID 不匹配。连接时,我需要分别匹配 ID 和类。所以基本上 #blah.newclass 将是 2 个单独的匹配项:#blah.newclass

有什么想法吗?

===================

最终解决方案

我最后使用 2 个正则表达式首先去除了 {} 之间的所有内容,然后根据剩余的输入简单地匹配选择器。

这是一个完整的工作示例:

//Grab contents of css file
$file = file_get_contents('css/style.css');

//Strip out everything between { and }
$pattern_one = '/(?<=\{)(.*?)(?=\})/s';

//Match any and all selectors (and pseudos)
$pattern_two = '/[\.|#][\w]([:\w]+?)+/';

//Run the first regex pattern on the input
$stripped = preg_replace($pattern_one, '', $file);

//Variable to hold results
$selectors = array();

//Run the second regex pattern on $stripped input
$matches = preg_match_all($pattern_two, $stripped, $selectors);

//Show the results
print_r(array_unique($selectors[0]));

最佳答案

[^a-z0-9][\w]+(?=\s)

我把你的 * 改成了 + 匹配

它在 RegEXR 中运行良好 - 一个很棒的正则表达式开发工具:http://gskinner.com/RegExr/ (桌面版下载见窗口右下角)

关于php - 使用 php 从源代码中提取 css 类和 ID,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10654654/

相关文章:

javascript - 使用 Bootstrap 进行同位素过滤

javascript - 当第一个初始元素没有与此 jquery 等效的某个类 CSS 时,选择下一个元素

javascript - 防止 Angular 自定义指令模板中禁用的树节点上的单击事件

php - 替换文本中的单词忽略 url

regex - Perl 中为什么需要括号来保存正则表达式的结果?

javascript - Android 原生浏览器不支持 JavaScript Regexp .match()?

php - 从查询中的日期时间中选择日期 - Yii2

PHP MySQL 复杂连接

php - MySQL 日期时间和时间戳字段是否比 Unix 时间戳整数更适合 PHP 应用程序?

javascript - 弹出视频容器流出