所以我试图用 php 从 CSS 文件中回显一些十六进制值,但我只想要每个 CSS 声明的十六进制值。 我只想返回包含 .u-fill- not .red 的声明中的那些
示例 CSS:
.red {
background-color: #ff0000 !important; }
.u-fill-grey-darker {
background-color: #222 !important; }
.u-fill-grey-dark {
background-color: #444 !important; }
.u-fill-grey-light {
background-color: #999 !important; }
我希望这个 php 能够像这样从 CSS 文件中给我一个十六进制列表:
#222
#444
#999
到目前为止,我可以像这样使用正则表达式匹配所有值:
[#\s\d]
但我想在 php foreach 循环中执行此操作。这可能吗?!
到目前为止,我的 php 看起来像这样:
<?php
$path = realpath(dirname(__FILE__) . '/../build/css/styles.css');
$css_contents = file_get_contents($path, true);
$lines = explode("\n", $css_contents);
?>
<div>
<?php foreach($lines as $line) :?>
<?php if($string = substr(trim($line), 0, 7) == '.u-fill') : ?>
<?php echo $string; ?>
<?php endif; ?>
<?php endforeach; ?>
</div>
预期输出
<div>#222</div>
<div>#444</div>
<div>#999</div>
但这不起作用,我不知道将正则表达式放在哪里以及使用哪个正则表达式。任何帮助将不胜感激。
最佳答案
您可以轻松地使用正则表达式:
$path = realpath(dirname(__FILE__) . '/../build/css/styles.css');
$css_contents = file_get_contents($path, true);
$matches;
preg_match_all('/\.u-fill-.*\n.*(#[0-9a-fA-F]+)/', $css_contents, $matches);
foreach($matches as $match) {
echo '<div>' . $match . '</div>';
}
关于php - 如何使用 REGEX php 从一系列 CSS 声明中提取十六进制值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40794529/