I\'m trying to write regex that extracts all hex colors from CSS code.
This is what I have now:
Code:
$css = <<
I'm not entirely sure if I got this right, but if you only want to match hex colors at the end of a CSS line:
preg_match_all('/#(?:[0-9a-fA-F]{6}|[0-9a-fA-F]{3})[\s;]*\n/',$css,$matches);
should work, all I did was add the optional \s;
char group (optional semi-colon and spaces) and a line-break character (not optional) and it seemed to work.
And as @GolezTrol pointed out #FFF;
is valid, too.
When tested on this:
$css = '/* Do not match me: #abcdefgh; I am longer than needed. */
.foo
{
color: #CAB;
background-color:#ababab;
}';
preg_match_all('/#(?:[0-9a-fA-F]{6}|[0-9a-fA-F]{3})[\s;]*\n/',$css,$matches);
var_dump($matches);
The output was:
array (array('#CAB;','#ababab;'))