Regex for matching CSS hex colors

后端 未结 5 1077
傲寒
傲寒 2021-02-02 07:33

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

This is what I have now:

Code:

$css = <<

        
5条回答
  •  死守一世寂寞
    2021-02-02 08:25

    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;'))
    

提交回复
热议问题