Skip to content

Instantly share code, notes, and snippets.

@pepebe
Last active May 14, 2018 15:44
Show Gist options
  • Select an option

  • Save pepebe/e45bb5389342052fd2dabca3396da405 to your computer and use it in GitHub Desktop.

Select an option

Save pepebe/e45bb5389342052fd2dabca3396da405 to your computer and use it in GitHub Desktop.
<?php
// by Bruno17 on slack
// Example: rgba([[+tv.node_activecolor:hextorgb]], 0.5)
$hexStr = $input;
$returnAsString = true;
$seperator = ',';
$hexStr = preg_replace("/[^0-9A-Fa-f]/", '', $hexStr); // Gets a proper hex string
$rgbArray = array();
if (strlen($hexStr) == 6) { //If a proper hex code, convert using bitwise operation. No overhead... faster
$colorVal = hexdec($hexStr);
$rgbArray['red'] = 0xFF & ($colorVal >> 0x10);
$rgbArray['green'] = 0xFF & ($colorVal >> 0x8);
$rgbArray['blue'] = 0xFF & $colorVal;
}
elseif (strlen($hexStr) == 3) { //if shorthand notation, need some string manipulations
$rgbArray['red'] = hexdec(str_repeat(substr($hexStr, 0, 1), 2));
$rgbArray['green'] = hexdec(str_repeat(substr($hexStr, 1, 1), 2));
$rgbArray['blue'] = hexdec(str_repeat(substr($hexStr, 2, 1), 2));
}
else {
return false; //Invalid hex color code
}
return $returnAsString ? implode($seperator, $rgbArray) : $rgbArray; // returns the rgb string or the associative array
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment