Last Updated: February 20, 2020
·
4.474K
· bluetidepro

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;
}

1 Response
Add your response

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

over 1 year ago ·