note 105635 deleted from function.hexdec by danbrown
| From: | danbrown@php.net | Date: | Fri, 02 Sep 2011 16:07:25 +0000 |
| Subject: | note 105635 deleted from function.hexdec by danbrown | ||
| References: | 1 | Groups: | php.notes |
| Request: | Send a blank email to php-notes+get-182904@lists.php.net to get a copy of this message | ||
Note Submitter: chanerec at gmail dot com
----
A derived function 'hex2RGB' from http://www.php.net/manual/en/function.hexdec.php#99478
with some improvements:
<code>
<?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 lenght 6
$hexStr = preg_replace("/[^0-f]/", '', $hexStr);
if( strlen($hexStr) == 3 )
$hexStr = preg_replace("/([0-9A-F])([0-9A-F])([0-9A-F])/i", '\1\1\2\2\3\3',
$hexStr);
#converhex2RGB
if (strlen($hexStr) == 6) {
$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 $returnAsString ? implode($seperator, $rgbResult) : $rgbResult;
}
return false; //Invalid hex color code
}
?>
</code>
Examples:
<code>
<?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
)
</code>