Search code examples
phpcolorshex

How to convert a string color to its hex code or RGB value?


I would like to create some sort of function where you pass in a string such as "yellow" or "green" and it returns its hex code or the range of hex codes that greens or yellows fit into.

Is this possible in PHP? If not possible, I am willing to try anything else that can do this!


Solution

  • There is no way to my knowledge to convert HTML color names or CSS color names to their Hex or RGB value in PHP. You'd have to create a map that knows the names (see Wiki article).

    Someone has done this work for you already:

    Excerpt:

    $Colors  =  ARRAY( 
        "black"=>array( "red"=>0x00,  "green"=>0x00,  "blue"=>0x00), 
        "maroon"=>array( "red"=>0x80,  "green"=>0x00,  "blue"=>0x00), 
        // ...
        // more colors inbetween
        // ...
        "wheat"=>array( "red"=>0xF5,  "green"=>0xDE,  "blue"=>0xB3), 
        "whitesmoke"=>array( "red"=>0xF5,  "green"=>0xF5,  "blue"=>0xF5), 
        "yellowgreen"=>array( "red"=>0x9A,  "green"=>0xCD,  "blue"=>0x32)
    ); 
    

    and then simply get the RGB values via $maroon = $Colors['maroon'];

    Further reference: