Regex for matching CSS hex colors

2022-08-30 13:13:36

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.


答案 1

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

Instead of you can also write , if the regex engine supports this posix character class. In this case you can skip the at the end, and the whole formula is only two characters more, but arguably more descriptive.[a-f0-9][[:xdigit:]]/i

/#([[:xdigit:]]{3}){1,2}\b/

答案 2

The accepted answer shows you how to do it with regex, because that was your question. But you really don't need to use regex for this. Normally this is how I would do it:

if(ctype_xdigit($color) && strlen($color)==6){
    // yay, it's a hex color!
}

for 100.000 iterations:

Regex solution *: 0.0802619457245 seconds

Xdigit with strlen: 0.0277080535889 seconds

*: hex: ([a-fA-F0-9]{6})


推荐