Skip to content

Instantly share code, notes, and snippets.

@abler98
Created December 6, 2016 11:58
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save abler98/00372549bec13116bf3dfbaf6d598b8e to your computer and use it in GitHub Desktop.
Save abler98/00372549bec13116bf3dfbaf6d598b8e to your computer and use it in GitHub Desktop.
<?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