Convert HEX to RGB with PHP

Andreas Zettl | 2 minute read

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.

<?php
    $sCSSString = '#77CCAA';
    #$sCSSString = '#7ca';

    $sTrimmedString = ltrim($sCSSString, '#');

After this, we need to handle the two different cases, standard and shorthand. 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;

The output should be:

    rgb(119, 204, 170)

Shorthand

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(
            function($sColor){ 
                return hexdec(str_repeat($sColor, 2)); 
            }, 
            str_split($sTrimmedString, 1)
        );
    } 

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

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

    rgb(119, 204, 170) 

🔙 Back to the article overview | Share on Twitter