note 106801 added to function.hexdec

From: Date: Wed, 07 Dec 2011 06:31:39 +0000
Subject: note 106801 added to function.hexdec
Groups: php.notes 
Request: Send a blank email to php-notes+get-184970@lists.php.net to get a copy of this message
<?php /** * Convert a hexa decimal color code to its RGB equivalent * * Code base: http://www.php.net/manual/en/function.hexdec.php#99478 * * @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) * */ function hex2RGB($hexStr, $returnAsString = false, $seperator = ',') { $hexStr = preg_replace('/[^0-9a-f]/i', '', $hexStr); // Gets a proper hex string //if shorthand notation, need some string manipulations if(strlen($hexStr) == 3) $hexStr = preg_replace('/([0-9A-F]{1})/i','$1$1',$hexStr); if ( strlen($hexStr) != 6) {//Invalid hex color code return false; } $rgbArray = array(); $colorVal = hexdec($hexStr); $rgbArray['red'] = 0xFF & ($colorVal >> 0x10); $rgbArray['green'] = 0xFF & ($colorVal >> 0x8); $rgbArray['blue'] = 0xFF & $colorVal; // returns the rgb string or the associative array return $returnAsString ? implode($seperator, $rgbArray) : $rgbArray; } OUTPUT: print_r(hex2RGB("#FF0")); print_r(hex2RGB("#FFFF00")); echo hex2RGB("#FF0", true)."\n"; echo hex2RGB("#FF0", true, ":")."\n"; ?> Array ( [red] => 255 [green] => 255 [blue] => 0 ) Array ( [red] => 255 [green] => 255 [blue] => 0 ) 255,255,0 255:255:0 ---- Server IP: 69.147.83.197 Probable Submitter: 200.76.90.173 ---- Manual Page -- http://www.php.net/manual/en/function.hexdec.php Edit -- https://master.php.net/note/edit/106801 Del: integrated -- https://master.php.net/note/delete/106801/integrated Del: useless -- https://master.php.net/note/delete/106801/useless Del: bad code -- https://master.php.net/note/delete/106801/bad+code Del: spam -- https://master.php.net/note/delete/106801/spam Del: non-english -- https://master.php.net/note/delete/106801/non-english Del: in docs -- https://master.php.net/note/delete/106801/in+docs Del: other reasons-- https://master.php.net/note/delete/106801 Reject -- https://master.php.net/note/reject/106801 Search -- https://master.php.net/manage/user-notes.php

« previous php.notes (#184970) next »