kwj0og
Last Updated: February 25, 2016
·
3.52K
· bluetidepro
6028b1c54dac0d98767d9efcb3d643b9

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;
}
Say Thanks
Respond

1 Response
Add your response

4650

Quick glance, but looks like your overlooked 0-9 in the PHP example "/[^a-f0-9]/i" instead ;)

over 1 year ago ·