Skip to content

Instantly share code, notes, and snippets.

@cesurapp
Last active January 10, 2020 08:16
Show Gist options
  • Save cesurapp/78251b309fdd36520830fd3cecc802d6 to your computer and use it in GitHub Desktop.
Save cesurapp/78251b309fdd36520830fd3cecc802d6 to your computer and use it in GitHub Desktop.
PHP Hex to RGBA
<?php
/**
* Hex to RGBA
*
* @param string $hexColor
* @param string|int|double $opacity
*
* @return string
*/
function hexToRgba(string $hexColor, $opacity = 1): string
{
// Remove # Chacter
if ($hexColor[0] === '#'){
$hexColor = substr($hexColor, 1);
}
// Convert to Array
if (strlen($hexColor) === 3) {
$hexColor = str_split($hexColor);
foreach ($hexColor as $index => $color) {
$hexColor[$index] = $color . $color;
}
} else if (strlen($hexColor) === 6){
$hexColor = str_split($hexColor, 2);
} else {
throw new Exception('Invalid Hex Color');
}
// Result to RGBA
return sprintf('rgba(%s, %s)', implode(',', array_map('hexdec', $hexColor)), $opacity);
}
@cesurapp
Copy link
Author

Example

hexToRgba('#AABBCC', 0.2)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment