What would be a good way to convert hex color values like #ffffff
into the single RGB values 255 255 255
using PHP?
If you want to convert hex to rgb you can use sscanf:
<?php
$hex = "#ff9900";
list($r, $g, $b) = sscanf($hex, "#%02x%02x%02x");
echo "$hex -> $r $g $b";
?>
Output:
#ff9900 -> 255 153 0
You can try this simple piece of code below.
list($r, $g, $b) = sscanf(#7bde84, "#%02x%02x%02x");
echo $r . "," . $g . "," . $b;
This will return 123,222,132
function RGB($hex = '')
{
$hex = str_replace('#', '', $hex);
if(strlen($hex) > 3) $color = str_split($hex, 2);
else $color = str_split($hex);
return [hexdec($color[0]), hexdec($color[1]), hexdec($color[2])];
}
Enjoy
public static function hexColorToRgba($hex, float $a){
if($a < 0.0 || $a > 1.0){
$a = 1.0;
}
for ($i = 1; $i <= 5; $i = $i+2){
$rgb[] = hexdec(substr($hex,$i,2));
}
return"rgba({$rgb[0]},{$rgb[1]},{$rgb[2]},$a)";
}
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' ) );
I've put @John's answer and @iic's comment/idea together into a function which can handle both, the usual hex color codes and the shorthand color codes.
A short explanation:
With scanf I read the r, g and b values from the hex color as strings. Not as hex values like in @John's answer. In case of using shorthand color codes, the r, g and b strings have to be doubled ("f" -> "ff" etc.) before converting them to decimals.
function hex2rgb($hexColor)
{
$shorthand = (strlen($hexColor) == 4);
list($r, $g, $b) = $shorthand? sscanf($hexColor, "#%1s%1s%1s") : sscanf($hexColor, "#%2s%2s%2s");
return [
"r" => hexdec($shorthand? "$r$r" : $r),
"g" => hexdec($shorthand? "$g$g" : $g),
"b" => hexdec($shorthand? "$b$b" : $b)
];
}