Last active
December 31, 2022 16:14
-
-
Save mrmolaei/9b4f744b469f820eda7049631c31d90d to your computer and use it in GitHub Desktop.
Convert Hex to RGB in PHP
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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