Created
December 6, 2016 11:58
-
-
Save abler98/00372549bec13116bf3dfbaf6d598b8e to your computer and use it in GitHub Desktop.
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 | |
function hex2rgb($color = '#fff') | |
{ | |
$color = ltrim($color, '#'); | |
$length = strlen($color); | |
if (preg_match('/[^0-9a-f]/i', $color) or $length <> 3 && $length <> 6) { | |
throw new Exception('Invalid color format'); | |
} | |
if ($length == 3) { | |
$color = preg_replace('/(.)/', '$1$1', $color); | |
} | |
$color = hexdec($color); | |
$r = 0xff & ($color >> 16); | |
$g = 0xff & ($color >> 8); | |
$b = 0xff & $color; | |
return sprintf('rgb(%d, %d, %d)', $r, $g, $b); | |
} | |
echo hex2rgb('#000') . PHP_EOL; // rgb(0, 0, 0) | |
echo hex2rgb('#ffffff') . PHP_EOL; // rgb(255, 255, 255) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment