Convert RGB to HEX with PHP

Getting the Color out of the CSS String

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)” this will not be covered here.

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


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

$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:


Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store