匹配CSS十六进制颜色的正则表达式 [英] Regex for matching CSS hex colors
问题描述
我试图编写从CSS代码中提取所有十六进制颜色的正则表达式。
这是我现在的情况:
代码:
$ css =<<<< CSS
/ *不匹配我:#abcdefgh;我比需要更长。 * /
.foo
{
color:#cccaaa; background-color:#ababab;
}
#bar
{
background-color:#123456
}
CSS;
preg_match_all('/#(?:[0-9a-fA-F] {6})/',$ css,$ matches);
输出:
code> Array
(
[0] => Array
(
[0] => #abcdef
[1] =& cccaaa
[2] => #ababab
[3] =>#123456
)
)
我不知道如何指定只匹配以标点符号,空格或换行符结尾的颜色。
解决方案由于十六进制颜色代码也可能包含3个字符,因此您可以定义一个强制性组和一个可选的字母和数字组,因此, be:
/#([af] | [AF] | [0-9]){3} ] | [AF] | [0-9]){3})?\b /
或者如果你想要一个漂亮和简短的版本,你可以说,你想要1或2组3个字母数字字符,并且他们应该匹配大小写不敏感(
/ i
)。/#([a-f0-9] {3}){1,2} \b / i
I'm trying to write regex that extracts all hex colors from CSS code.
This is what I have now:
Code:
$css = <<<CSS /* Do not match me: #abcdefgh; I am longer than needed. */ .foo { color: #cccaaa; background-color:#ababab; } #bar { background-color:#123456 } CSS; preg_match_all('/#(?:[0-9a-fA-F]{6})/', $css, $matches);
Output:
Array ( [0] => Array ( [0] => #abcdef [1] => #cccaaa [2] => #ababab [3] => #123456 ) )
I don't know how to specify that only those colors are matched which ends with punctuation, whitespace or newline.
解决方案Since a hex color code may also consist of 3 characters, you can define a mandatory group and an optional group of letters and digits, so the long and elaborate notation would be:
/#([a-f]|[A-F]|[0-9]){3}(([a-f]|[A-F]|[0-9]){3})?\b/
Or if you want a nice and short version, you can say that you want either 1 or 2 groups of 3 alphanumeric characters, and that they should be matched case insensitively (
/i
)./#([a-f0-9]{3}){1,2}\b/i
这篇关于匹配CSS十六进制颜色的正则表达式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!