note 105635 added to function.hexdec

From: Date: Fri, 02 Sep 2011 16:01:58 +0000
Subject: note 105635 added to function.hexdec
Groups: php.notes 
Request: Send a blank email to php-notes+get-182903@lists.php.net to get a copy of this message
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> ---- Server IP: 69.147.83.197 Probable Submitter: 189.130.16.152 ---- Manual Page -- http://www.php.net/manual/en/function.hexdec.php Edit -- https://master.php.net/note/edit/105635 Del: integrated -- https://master.php.net/note/delete/105635/integrated Del: useless -- https://master.php.net/note/delete/105635/useless Del: bad code -- https://master.php.net/note/delete/105635/bad+code Del: spam -- https://master.php.net/note/delete/105635/spam Del: non-english -- https://master.php.net/note/delete/105635/non-english Del: in docs -- https://master.php.net/note/delete/105635/in+docs Del: other reasons-- https://master.php.net/note/delete/105635 Reject -- https://master.php.net/note/reject/105635 Search -- https://master.php.net/manage/user-notes.php

« previous php.notes (#182903) next »