王新阳

wangxinyang

PHP十六进制和RGB颜色互换

两个函数均未进行数据合法性验证:
十六进制颜色 preg_match('/^#([0-9a-f]{3}|[0-9a-f]{6})$/i', $hex)===1
RGB三个值均大于等于0小于等于255

function hex2rgb($hex) {
	$hex = str_replace("#", "", $hex);
	if(strlen($hex) == 3){
		$r = hexdec(substr($hex,0,1).substr($hex,0,1));
		$g = hexdec(substr($hex,1,1).substr($hex,1,1));
		$b = hexdec(substr($hex,2,1).substr($hex,2,1));
	}else{
		$r = hexdec(substr($hex,0,2));
		$g = hexdec(substr($hex,2,2));
		$b = hexdec(substr($hex,4,2));
	}
	return array($r, $g, $b);
}


function rgb2hex($rgb) {
	if(!is_array($rgb)) $rgb=explode(',', $rgb);
	$hex = "#";
	$hex .= str_pad(dechex((int)$rgb[0]), 2, "0", STR_PAD_LEFT);
	$hex .= str_pad(dechex((int)$rgb[1]), 2, "0", STR_PAD_LEFT);
	$hex .= str_pad(dechex((int)$rgb[2]), 2, "0", STR_PAD_LEFT);
	return $hex; 
}
2016-05-15
2025-04-05 星期六 农历三月初八