Convert hex color to RGB values in PHP

前端 未结 15 1838
轮回少年
轮回少年 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:33

    Convert Color Code HEX to RGB

    $color = '#ffffff';
    $hex = str_replace('#','', $color);
    if(strlen($hex) == 3):
       $rgbArray['r'] = hexdec(substr($hex,0,1).substr($hex,0,1));
       $rgbArray['g'] = hexdec(substr($hex,1,1).substr($hex,1,1));
       $rgbArray['b'] = hexdec(substr($hex,2,1).substr($hex,2,1));
    else:
       $rgbArray['r'] = hexdec(substr($hex,0,2));
       $rgbArray['g'] = hexdec(substr($hex,2,2));
       $rgbArray['b'] = hexdec(substr($hex,4,2));
    endif;
    
    print_r($rgbArray);
    

    Output

    Array ( [r] => 255 [g] => 255 [b] => 255 )
    

    I have found this reference from here - Convert Color Hex to RGB and RGB to Hex using PHP

提交回复
热议问题