Skip to content

Instantly share code, notes, and snippets.

@mrmolaei
Last active December 31, 2022 16:14
Show Gist options
  • Save mrmolaei/9b4f744b469f820eda7049631c31d90d to your computer and use it in GitHub Desktop.
Save mrmolaei/9b4f744b469f820eda7049631c31d90d to your computer and use it in GitHub Desktop.
Convert Hex to RGB in PHP
<?php
function hexToRgb( $hex )
{
// Convert hex to RGB
if (strlen($hex) == 7) {
$rgb = array_map('hexdec', str_split(ltrim($hex, '#'), 2));
} else {
$hex = '#' . implode( "", array_map( function($digit) {
return str_repeat($digit, 2);
}, str_split(ltrim($hex, '#'), 1)) );
$rgb = array_map('hexdec', str_split(ltrim($hex, '#'), 2));
}
$rgb = 'rgb(' . implode( ", ", $rgb ) . ')';
return $rgb;
}
echo hexToRgb( "#333" ); // rgb(51, 51, 51)
echo hexToRgb( "#333333" ); // rgb(51, 51, 51)
echo hexToRgb( "#fff" ); // rgb(255, 255, 255)
echo hexToRgb( "#000000" ); // rgb(0, 0, 0)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment