Convert RGB to HEX with PHP

Andreas Zettl | 4 minute read

Getting the Color out of the CSS String

To convert an RGB string like "rgb(114, 193, 44)" to HEX we first need to get the three color values for red, green and blue out of the string, in this article we only talk about RGB strings with the integer value representation, the below sample will not work for three percentage values. We need to consider that there is also RGBA for colors with an alpha channel with a syntax like "rgba(255, 13, 12, 0.5)" as hex does not support alpha channels (see "Unlike RGB values, there is no hexadecimal notation for an RGBA value.") we will only use the color values here too.


To get the colors out of the string, we will use a regular expression.

/rgba?\(\s?([0-9]{1,3}),\s?([0-9]{1,3}),\s?([0-9]{1,3})/i

The regex above matches any string starting with "rgb", checks for an optional "a", then for the bracket and the first number between 0 and 999. After the first number, a comma is expected and then space or directly the next number. This regular expression only matches until the third number and does not check further for the alpha channel or if there is a closing bracket. You can find more detailed regular expressions on the internet which check if it is a valid RGB color we, for example, will check if the numbers are not higher than 255 in our PHP code.

The PHP Part

We start with a simple PHP file which contains our CSS string and the regex to get the colors out of the string.

<?php
    $sCSSString = 'rgba(114, 193, 44)';
    $sRegex     = '/rgba?\(\s?([0-9]{1,3}),\s?([0-9]{1,3}),\s?([0-9]{1,3})/i';

    preg_match($sRegex, $sCSSString, $matches);

    if(count($matches) != 4){
        die('The color count does not match.');
    }

    $iRed   = (int) $matches[1];
    $iGreen = (int) $matches[2]; 
    $iBlue  = (int) $matches[3];

    print_r($iRed . ' ' . $iGreen . ' ' . $iBlue);

This code should return you 114 193 44, now as mentioned above we need to check if the color values are lower or equal to 255.

    if($iRed > 255 || $iGreen > 255 || $iBlue > 255){
        die('One of the color values is above 255.');
    }

Now that we only have valid color values, we can start the conversion part. To convert the numbers, we use the PHP function dechex to convert the decimal number to hexadecimal.

    $sHexValue = dechex($iRed) . dechex($iGreen) . dechex($iBlue);

    echo '#' . $sHexValue;

In the end the output should be:

    #72c12c
Learn to Code with this Udacity Course: Introduction to ProgrammingAdvertisment🛈

🔙 Back to the article overview | Share on Twitter