我正在尝试使用 php 从 css 文件中提取颜色。这些颜色可能是:
- 正常颜色(颜色:#xxxxxx;)
- 背景颜色(背景:#xxxxxx;/背景:...#xxxxxx ...;)
- 背景渐变(背景图像:线性渐变(顶部,#xxxxxx,#xxxxxx);
- 有时颜色可能是 3 个字符(例如:#fff)
我尝试使用 preg match 返回以 # 开头的单词
preg_match_all('/(?!\b)(#\w+\b)/', $css_text, $matches)
...但它也返回 DIV Id(#header 等)
展望未来,我还希望我们的代码返回一个多维数组,其中不仅包含颜色代码,还包含找到它的行号。
请帮忙!:)
---------- 编辑:问题已解决 ----------
谢谢大家的回答,我把大家的答案结合起来了。因为我想将正则表达式保持在最低限度,所以这就是我用作最终工作代码的代码:
$css = file_get_contents("style.css");
$token = strtok($css, "{}");
$css_parts = array();
while ($token !== false) {
$css_parts[] = trim($token);
$token = strtok("{}");
}
$flag = false; $properties = "";
foreach($css_parts as $part) {
if($flag) { $properties .= " ".trim($part); }
$flag = !$flag;
}
$properties = strtoupper(str_replace(array(":",",",";","(",")")," ",$properties));
$colors = array();
preg_match_all('/(?!\b)(#\w+\b)/',$properties,$colors);
$colors = array_unique($colors[0]);
print_r($colors);