PSD to HTML conversion PSD to HTML conversion PSD2HTML.com with over 300 professionals takes the designs to HTML and beyond

Code Snippet

Home » Code Snippets » PHP » Convert HEX to RGB

Convert HEX to RGB

Give function hex code (e.g. #eeeeee), returns array of RGB values.

function hex2rgb( $colour ) {
        if ( $colour[0] == '#' ) {
                $colour = substr( $colour, 1 );
        }
        if ( strlen( $colour ) == 6 ) {
                list( $r, $g, $b ) = array( $colour[0] . $colour[1], $colour[2] . $colour[3], $colour[4] . $colour[5] );
        } elseif ( strlen( $colour ) == 3 ) {
                list( $r, $g, $b ) = array( $colour[0] . $colour[0], $colour[1] . $colour[1], $colour[2] . $colour[2] );
        } else {
                return false;
        }
        $r = hexdec( $r );
        $g = hexdec( $g );
        $b = hexdec( $b );
        return array( 'red' => $r, 'green' => $g, 'blue' => $b );
}

Subscribe to The Thread

  1. Thanks, I used it as a good starting point.
    I’ve updated it slightly to be shorter and with the assumption the end hex is always 6 characters (as I control the input). The str_split() might be helpful for your code maybe?

    function($hexString){
    $hexString = preg_replace(“/[^abcdef]/i”,”",$hexString);
    if(strlen($hexString)==6){
    list($r,$g,$b) = str_split($hexString,2);
    return Array(“r”=>hexdec($r),”g”=>hexdec($g),”b”=>hexdec($b));
    }

    • I just realised I didn’t copy the entire code.
      There’s a false missing off the end! heh….

      function hex2rgb($hexString){
      $hexString = preg_replace(“/[^abcdef]/i”,”",$hexString);
      if(strlen($hexString)==6){
      list($r,$g,$b) = str_split($hexString,2);
      return Array(“r”=>hexdec($r),”g”=>hexdec($g),”b”=>hexdec($b));
      }
      return false;
      }

  2. If anyone is interested in a javascript equivalent I used this (Not perfect but seems to do the job) :

    function hex2rgb( colour ) {
    var r,g,b;
    if ( colour.charAt(0) == ‘#’ ) {
    colour = colour.substr(1);
    }

    r = colour.charAt(0) + ” + colour.charAt(1);
    g = colour.charAt(2) + ” + colour.charAt(3);
    b = colour.charAt(4) + ” + colour.charAt(5);

    r = parseInt( r,16 );
    g = parseInt( g,16 );
    b = parseInt( b ,16);
    return “rgb(” + r + “,” + g + “,” + b + “)”;
    }

Speak, my friend

At this moment, you have an awesome opportunity* to be the person your mother always wanted you to be: kind, helpful, and smart. Do that, and we'll give you a big ol' gold star for the day (literally).

Posting tips:
  • You can use basic HTML
  • When posting code, please turn all
    < characters into &lt;
  • If the code is multi-line, use
    <pre><code></code></pre>
Thank you,
~ The Management ~