Convert HEX to RGB with PHP

To convert a HEX string like "#77CCAA" or "#7ca" to the RGB Version "rgb(119, 204, 170)" we first need to remove the "#" from the string. After this we need to handle the two different cases, standard and shorthand.

    $sCSSString = '#77CCAA';
    #$sCSSString = '#7ca';

    $sTrimmedString = ltrim($sCSSString, '#');
📋 Copy Code

First, we will handle the standard case where we have to split the string with the PHP method str_split and a split length of two. As a result, we get an array with the three elements "77", "CC" and "AA".

Now similar to the function to convert decimal to hexadecimal, this time we need to use the reverse hexdec on each of the elements of the array. Here another PHP function comes in handy, array_map which applies a callback on each element.

    list($iRed, $iGreen, $iBlue) = array_map('hexdec', str_split($sTrimmedString, 2));

    echo $iRed . ', ' . $iGreen . ', ' . $iBlue;
📋 Copy Code

The output should be:

    rgb(119, 204, 170)
📋 Copy Code


Time to check whether we got a three-digit value and if so split the string with a split length of one and then repeat the array elements with str_repeat two times before passing them to the hexdec function.

    if(strlen($sTrimmedString) === 3){
        list($iRed, $iGreen, $iBlue) = array_map(
                return hexdec(str_repeat($sColor, 2)); 
            str_split($sTrimmedString, 1)

    echo 'rgb(' . $iRed . ', ' . $iGreen . ', ' . $iBlue . ')'; 
📋 Copy Code

If you uncomment the second line now the output for the second echo should be:

    rgb(119, 204, 170) 
📋 Copy Code