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.
if(ctype_xdigit($color) && strlen($color)==6)
. – Fillet#
inside the string$color
, otherwisectype_xdigit($color)
returns false. – Faythe