Skip to content

Instantly share code, notes, and snippets.

@relliv
Created February 26, 2019 18:56
Show Gist options
  • Save relliv/42c36b1389cffb1bf613f6f6ebefa47b to your computer and use it in GitHub Desktop.
Save relliv/42c36b1389cffb1bf613f6f6ebefa47b to your computer and use it in GitHub Desktop.
PHP HEX to RGBa
<?php
/**
* Hex to RGBa
*
* @param string $color: hex color
* @param bool|float $opacity: alpha channel, optional
* @param string $default: default return value
*/
function hex2rgba($color, $opacity = false, $default = 'rgb(0,0,0)')
{
preg_match('/#?([a-fA-F-0-9]{3,8})/', $color, $match);
if ($match){
preg_match_all('/#?([a-fA-F-0-9]{1,2})([a-fA-F-0-9]{1,2})([a-fA-F-0-9]{1,2})/', $color, $matches);
if ($matches){
unset($matches[0]);
foreach ($matches as $key => $value) {
$matches[$key] = $value[0];
}
// hexadec to rgb
$rgb = implode(',', array_map('hexdec', $matches));
// set alpha channel
if ($opacity) {
$opacity = (float)$opacity > 1 ? 1 : $opacity;
return "rgba({$rgb}, {$opacity})";
}
// default rgb color
return "rgb({$rgb})";
}
}
return $default ? $default : 'rgb(0,0,0)';
}
echo '<body style="background-color: green">Egoi Develoer Egoist Developer Developer mi Egoist <div style="background-color: '.hex2rgba('#4286f4', .3).'; height: 600px; width: 600px;"></div></body>';
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment