The issue I've seen with the existing hex to dec conversion routines is the lack of error-trapping. I stick to the theory that one should try to cover ALL the bases when writing a generalized routine such as this one. I have a varied background that covers a wide variety of design/development languages, on the web as well as desktop apps. As such I've seen multiple formats for writing hex colors.



For example, the color red COULD be written as follows:

#ff0000

&Hff0000

#ff

&Hff



Therefore I have written a function that is case-insensitive and takes into account the chance that different developers have a tendency to format hex colors in different ways.



<?php

function convert_color ( $hex ){

$len = strlen ( $hex );

$chars = array( "#" , "&" , "H" , "h" );

$hex = strip_chars ( $hex , $chars );

preg_match ( "/([0-9]|[A-F]|[a-f]){" . $len . "}/i" , $hex , $arr );

$hex = $arr [ 0 ];

if ( $hex ) {

switch( $len ) {

case 2 :

$red = hexdec ( $hex );

$green = 0 ;

$blue = 0 ;

break;

case 4 :

$red = hexdec ( substr ( $hex , 0 , 2 ));

$green = hexdec ( substr ( $hex , 2 , 2 ));

$blue = 0 ;

break;

case 6 :

$red = hexdec ( substr ( $hex , 0 , 2 ));

$green = hexdec ( substr ( $hex , 2 , 2 ));

$blue = hexdec ( substr ( $hex , 4 , 2 ));

break;

};

$color [ success ] = true ;

$color [ r ] = $red ;

$color [ g ] = $green ;

$color [ b ] = $blue ;

return $color ;

} else {

$color [ success ] = false ;

$color [ error ] = "unable to convert hex to dec" ;

};

}



function strip_chars ( $string , $char ){

$len = strlen ( $string );

$count = count ( $char );

if ( $count >= 2 ) {

for ( $i = 0 ; $i <= $count ; $i ++) {

if ( $char [ $i ]) {

$found = stristr ( $string , $char [ $i ]);

if ( $found ) {

$val = substr ( $string , $found + 1 , $len - 1 );

$string = $val ;

};

};

};

} else {

$found = stristr ( $string , $char );

if ( $found ) {

$val = substr ( $string , $found + 1 , $len - 1 );

};

};

echo $val ;

return $val ;

}



?>



As you can see, the function "convert_color" accepts a hex # in most acceptable formats and returns an associative array. [success] is set to TRUE if the function succeeds and FALSE if not. The array members [r], [g] and [b] hold the red,green and blue values respectively. If it fails, [error] holds a custom error message.



"strip_chars" is a support function written to remove the unwanted characters from the hex string, and sends the concatenated string back to the calling function. It will accept either a single value or an array of values for the characters to remove.