Convert hex color to RGB values in PHP

前端 未结 15 1857
轮回少年
轮回少年 2020-11-30 21:32

What would be a good way to convert hex color values like #ffffff into the single RGB values 255 255 255 using PHP?

15条回答
  •  误落风尘
    2020-11-30 22:16

    My approach to take care of hex colors with or without hash, single values or pair values:

    function hex2rgb ( $hex_color ) {
        $values = str_replace( '#', '', $hex_color );
        switch ( strlen( $values ) ) {
            case 3;
                list( $r, $g, $b ) = sscanf( $values, "%1s%1s%1s" );
                return [ hexdec( "$r$r" ), hexdec( "$g$g" ), hexdec( "$b$b" ) ];
            case 6;
                return array_map( 'hexdec', sscanf( $values, "%2s%2s%2s" ) );
            default:
                return false;
        }
    }
    // returns array(255,68,204)
    var_dump( hex2rgb( '#ff44cc' ) );
    var_dump( hex2rgb( 'ff44cc' ) );
    var_dump( hex2rgb( '#f4c' ) );
    var_dump( hex2rgb( 'f4c' ) );
    // returns false
    var_dump( hex2rgb( '#f4' ) );
    var_dump( hex2rgb( 'f489' ) );
    

提交回复
热议问题