Hemaulo Hemaulo - 7 months ago 35
PHP Question

Regex for matching CSS hex colors

I'm trying to write regex that extracts all hex colors from CSS code.

This is what I have now:


$css = <<<CSS

/* Do not match me: #abcdefgh; I am longer than needed. */

color: #cccaaa; background-color:#ababab;


preg_match_all('/#(?:[0-9a-fA-F]{6})/', $css, $matches);


[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:


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).