【发布时间】:2013-02-11 19:11:47
【问题描述】:
我正在尝试使用 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);
【问题讨论】:
-
如果你扩展你的表达式以包含冒号,那应该注意 div id
-
@JeffHawthorne 我考虑过,但有时“:”和“#”之间可能有一个或多个空格 - 另外,我认为它不会涵盖我的需求列表的案例 2 和 3,正确如果我错了,我 - 我不是写这些表达的专家!
-
我实际上只是在阅读这方面的内容。您可以使用“:*#”来告诉它处理冒号和#之间的任意数量的空格。星号表示 0 到 n 次,如果您知道至少会有一个空格,则加号有效
-
@JeffHawthorne 明白了。但是如果我们有 [background: url() #xxx;] 或 [background-image: linear-gradient(top, #xxxxxx, #xxxxxx] ??
-
对了,你是不是也需要找
rgbacolors...?例如 - 请参阅您的 css 示例输出的第 38 行末尾。
标签: php javascript search preg-match extract