Created
September 2, 2011 16:02
-
-
Save fitorec/1189016 to your computer and use it in GitHub Desktop.
Convert a hexa decimal color code to its RGB equivalent
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| <?php print_r(hex2RGB('00ff67')); ?> | |
| #Out | |
| Array | |
| ( | |
| [red] => 0 | |
| [green] => 255 | |
| [blue] => 103 | |
| ) | |
| <?php echo hex2RGB('#00ff67',true ); ?> | |
| __#Out__ | |
| 0,255,103 | |
| <?php echo hex2RGB('#2f6',true ); ?> | |
| __#Out__ | |
| 34,255,102 | |
| <?php echo hex2RGB('#22ff66',true ); ?> | |
| __#Out__ | |
| 34,255,102 | |
| <?php print_r(hex2RGB('##22ff66')); ?> | |
| __#Out__ | |
| Array | |
| ( | |
| [red] => 34 | |
| [green] => 255 | |
| [blue] => 102 | |
| ) |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| <?php | |
| /** | |
| * Convert a hexa decimal color code to its RGB equivalent | |
| * | |
| * @param string $hexStr (hexadecimal color value) | |
| * @param boolean $returnAsString (if set true, returns the value separated by the separator character. Otherwise returns associative array) | |
| * @param string $seperator (to separate RGB values. Applicable only if second parameter is true.) | |
| * @return array or string (depending on second parameter. Returns False if invalid hex color value) | |
| * @base-link: http://www.php.net/manual/en/function.hexdec.php#99478 | |
| */ | |
| function hex2RGB($hexStr, $returnAsString = false, $seperator = ',') { | |
| # Normalize a proper hex string with length 6 | |
| $hexStr = preg_replace("/[^0123456789abcdef]/", '',strtolower($hexStr)); | |
| if( strlen($hexStr) == 3 ) | |
| $hexStr = preg_replace("/(.)(.)(.)/", '\1\1\2\2\3\3', $hexStr); | |
| #converHex2RGB | |
| if (preg_match('/^[0123456789abcdef]{6}$/',$hexStr)) { | |
| $rgbResult=array(); | |
| #2 characters will correspond to each color | |
| foreach(array('red','green','blue') as $str_pos=>$color_index) | |
| $rgbResult[$color_index]=hexdec(substr($hexStr,2*$str_pos,2)); | |
| #return array o string depending on second paramenter | |
| return $returnAsString ? implode($seperator, $rgbResult) : $rgbResult; | |
| } | |
| return false; //Invalid hex color code | |
| } | |
| ?> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment