Convert HEX to RGB (jQuery or PHP)
I was working on a project that needed to convert HEX to RGB and came up with these after some digging and tweaking. I figured I would share for anyone else who might ever need these nice functions.
PHP:
function hex2rgb($hex){
$hex = preg_replace(“/[^abcdef]/i”,”",$hex);
if(strlen($hex)==6){
list($r,$g,$b) = str_split($hex,2);
return Array(“r”=>hexdec($r),”g”=>hexdec($g),”b”=>hexdec($b));
}
return false;
}
jQuery:
hex2rgb: function(hex) {
var result = /^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(hex);
return result ? {
r: parseInt(result[1], 16),
g: parseInt(result[2], 16),
b: parseInt(result[3], 16),
rgb: parseInt(result[1], 16) + ", " + parseInt(result[2], 16) + ", " + parseInt(result[3], 16)
} : null;
}Written by Zach Reed
Related protips
1 Response
Quick glance, but looks like your overlooked 0-9 in the PHP example "/[^a-f0-9]/i" instead ;)
over 1 year ago
·
Have a fresh tip? Share with Coderwall community!
Post
Post a tip
Best
#Php
Authors
Did you know?
JavaScript on a page runs with the privileges of that origin. One altered library, tag manager, or snippet can read inputs, change what people see, and call your APIs as the user.
Security insights from Cside
Sponsored by #native_company# — Learn More
#native_title#
#native_desc#