This article will explain how to convert color code from HEX to RGB or HEX to RGB using PHP. We have created a PHP function for converting the color code to RGB or HEX. rgb2hex2rgb() function makes color conversion simple.
rgb2hex2rgb() function accept one parameter ($color) with two types of value RGB or HEX.
$color => Required, from which you want to convert.
Returns RGB format color code as an array if Hex color code is passed into $color parameter. Returns HEX format color code as a string if RGB color code is passed into $color parameter.
rgb2hex2rgb() function is given below:/**
*
* Author: CodexWorld
* Author URI: http://www.codexworld.com
* Function Name: rgb2hex2rgb()
* $color => HEX or RGB
* Returns RGB or HEX color format depending on given value.
*
**/
function rgb2hex2rgb($color){
if(!$color) return false;
$color = trim($color);
$result = false;
if(preg_match("/^[0-9ABCDEFabcdef\#]+$/i", $color)){
$hex = str_replace('#','', $color);
if(!$hex) return false;
if(strlen($hex) == 3):
$result['r'] = hexdec(substr($hex,0,1).substr($hex,0,1));
$result['g'] = hexdec(substr($hex,1,1).substr($hex,1,1));
$result['b'] = hexdec(substr($hex,2,1).substr($hex,2,1));
else:
$result['r'] = hexdec(substr($hex,0,2));
$result['g'] = hexdec(substr($hex,2,2));
$result['b'] = hexdec(substr($hex,4,2));
endif;
}elseif (preg_match("/^[0-9]+(,| |.)+[0-9]+(,| |.)+[0-9]+$/i", $color)){
$rgbstr = str_replace(array(',',' ','.'), ':', $color);
$rgbarr = explode(":", $rgbstr);
$result = '#';
$result .= str_pad(dechex($rgbarr[0]), 2, "0", STR_PAD_LEFT);
$result .= str_pad(dechex($rgbarr[1]), 2, "0", STR_PAD_LEFT);
$result .= str_pad(dechex($rgbarr[2]), 2, "0", STR_PAD_LEFT);
$result = strtoupper($result);
}else{
$result = false;
}
return $result;
}
Use rgb2hex2rgb() function like the following.
$hexString = rgb2hex2rgb('255,255,255');
$rgbArray = rgb2hex2rgb('#FFFFFF');
Looking for expert assistance to implement or extend this script’s functionality? Submit a Service Request
💰 Budget-friendly • 🌍 Global clients • 🚀 Production-ready solutions
nice tankyou
Good afternoon! I tried your function at work – for some reason, it returns an incorrect result ..
$ rgb_only = “0, 255, 0”;
$ hex_accent_color = rgb2hex2rgb ($ rgb_only);
Returns: # 0000FF is Violet instead of pure green !?
Must be: “0, 255, 0” -> 00ff00
And the function returns: “0, 255, 0” -> 0000ff