因此,我试图减少一些代码,并使用PHP函数preg_replace()做到这一点。我正在尝试压缩十六进制颜色。例如:
#FF0000 => #F00
我在互联网上找到了一些代码,到目前为止,这就是我所拥有的:
$hex_char = '[a-f0-9]';
$html = preg_replace("/(?<=^#)($hex_char)\\1($hex_char)\\2($hex_char)\\3\z/i", '\1\2\3', $html);
它适用于像这样的字符串:
$html = "#FF0000";
好的,所以真正的问题是我需要代码来搜索诸如CSS等代码块中的所有十六进制颜色。这将是这样的:
<?php
$html = '
.this{
color: #FF0000;
background-color: #CCCCCC;
}
';
$hex_char = '[a-f0-9]';
$html = preg_replace("/(?<=^#)($hex_char)\\1($hex_char)\\2($hex_char)\\3\z/i", '\1\2\3', $html);
echo $html;
?>
我怎样才能做到这一点?谢谢!
从您的正则表达式中删除字符串锚的后面和结尾。
<?php
$html = <<<EOT
.this{
color: #FF0000;
background-color: #CCCCCC;
}
EOT;
$hex_char = '[a-f0-9A-F]';
$html = preg_replace("~#($hex_char)\\1($hex_char)\\2($hex_char)\\3~", '#$1$2$3', $html);
echo $html;
?>
输出:
.this{
color: #F00;
background-color: #CCC;
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句