Simple PHP function to convert hexadecimal colors to RGB (red, green, blue) decimal values

This function will convert hexadecimal colors with a length of 6, 3, 2, or 1 into their RGB decimal equivalents. If a value cannot be converted, it defaults to black…

function hex2rgb($hex = NULL) {
	preg_match('/^#{0,1}([0-9a-f]{1,6})$/i', $hex, $matches);
	if ($hex[0] == '#') $hex = substr($hex, 1);
	$length = @strlen($matches[1]);
	switch ($length) {
		case 6:
			$rgb = array($hex[0] . $hex[1], $hex[2] . $hex[3], $hex[4] . $hex[5]);
			break;
		case 3:
			$rgb = array($hex[0] . $hex[0], $hex[1] . $hex[1], $hex[2] . $hex[2]);
			break;
		case 2:
			$rgb = array($hex[0] . $hex[1], $hex[0] . $hex[1], $hex[0] . $hex[1]);
			break;
		default:
			$hex = ($length == 1) ? $hex . $hex : 0;
			$rgb = array($hex, $hex, $hex);
			break;
	}
	return array(
		'r' => hexdec($rgb[0]),
		'g' => hexdec($rgb[1]),
		'b' => hexdec($rgb[2])
	);
}

Short, simple and sweet 🙂

Leave a Reply

Your email address will not be published. Required fields are marked *