Converting hexadecimal color values to RGB

Sunday, October 07, 2007   —   Vienna 0 Comments

A useful function to convert a hexadecimal color value to an array of RGB values.

function Hex2RGB($c)
{
	if(!$c) { return false; }

	$c = trim($c);
	$rgb = false;

	if(eregi("^[0-9ABCDEFabcdef\#]+$", $c))
	{
		$c = str_replace('#','', $c);
		$l = strlen($c);
		if($l == 3)
		{
			for($i=0; $i<3; $i++) { $c6 .= substr($c, $i,1) . substr($c, $i,1); }
			$c = $c6;
		}
		unset($rgb);
		$rgb[0] = $rgb['r'] = $rgb['red']   = hexdec(substr($c, 0,2));
		$rgb[1] = $rgb['g'] = $rgb['green'] = hexdec(substr($c, 2,2));
		$rgb[2] = $rgb['b'] = $rgb['blue']  = hexdec(substr($c, 4,2));
	}
	else { $rgb = false; }
 
	return $rgb;
}

Add a comment

The fields that are highlighted contain errors
Name:
Email:     (Not shown)
Website:
Comment:
  Notify me when my comment has been cleared.
  Notify me of followup comments.