note 53529 added to function.hexdec
| From: | bishop at osu1 dot php dot net | Date: | Sun, 05 Jun 2005 02:51:29 +0000 |
| Subject: | note 53529 added to function.hexdec | ||
| Groups: | php.notes | ||
| Request: | Send a blank email to php-notes+get-89928@lists.php.net to get a copy of this message | ||
Bullet-proof hex-to-rgb colour converter like brian at sagesport dot com wanted, just far fewer code
lines. As a bonus, gives you the ability to return as string or array:
<?php
function &hex2rgb($hex, $asString = true)
{
// strip off any leading #
if (0 === strpos($hex, '#')) {
$hex = substr($hex, 1);
} else if (0 === strpos($hex, '&H')) {
$hex = substr($hex, 2);
}
// break into hex 3-tuple
$cutpoint = ceil(strlen($hex) / 2)-1;
$rgb = explode(':', wordwrap($hex, $cutpoint, ':', $cutpoint), 3);
// convert each tuple to decimal
$rgb[0] = (isset($rgb[0]) ? hexdec($rgb[0]) : 0);
$rgb[1] = (isset($rgb[1]) ? hexdec($rgb[1]) : 0);
$rgb[2] = (isset($rgb[2]) ? hexdec($rgb[2]) : 0);
return ($asString ? "{$rgb[0]} {$rgb[1]} {$rgb[2]}" : $rgb);
}
?>
Handles 2, 3, and 6 character colour codes with leading # or &H.
----
Manual Page -- http://www.php.net/manual/en/function.hexdec.php
Edit -- http://master.php.net/manage/user-notes.php?action=edit+53529
Delete: added to the manual -- http://master.php.net/manage/user-notes.php?action=delete+53529&report=yes&reason=added+to+the+manual
Delete: bad code -- http://master.php.net/manage/user-notes.php?action=delete+53529&report=yes&reason=bad+code
Delete: spam -- http://master.php.net/manage/user-notes.php?action=delete+53529&report=yes&reason=spam
Delete: useless -- http://master.php.net/manage/user-notes.php?action=delete+53529&report=yes&reason=useless
Delete: other reasons -- http://master.php.net/manage/user-notes.php?action=delete+53529&report=yes
Reject -- http://master.php.net/manage/user-notes.php?action=reject+53529&report=yes
Search -- http://master.php.net/manage/user-notes.php