Site icon Weblizar Blog

How to convert Hex code to RGB code in php

Here Are some Steps to convert Hex color code to RGB color Code

Step-1 :  First write your php function for convert Hex color

function hex2rgb($hex) {
$hex = str_replace("#", "", $hex);

if(strlen($hex) == 3) {
$r = hexdec(substr($hex,0,1).substr($hex,0,1));
$g = hexdec(substr($hex,1,1).substr($hex,1,1));
$b = hexdec(substr($hex,2,1).substr($hex,2,1));
} else {
$r = hexdec(substr($hex,0,2));
$g = hexdec(substr($hex,2,2));
$b = hexdec(substr($hex,4,2));
}
$rgb = array($r, $g, $b);

return $rgb; // returns an array with the rgb values
}

Step-2  :  Call this function everywhere where you want to get converted hex color code here an example that how to call this fucntion

$Hex_color = "#31A#DD";
$RGB_color = hex2rgb($Hex_color);

 

Step-3  :  Echo this variable at where there you want to show rgb color but first implode this variable using comma here an example

$Final_Rgb_color = implode(", ", $RGB_color);

 

Step-4 :  Use this code in style , Here is an example

<style>

.container {

background : rgba(<?php echo $Final_Rgb_color;  ?>,1);

}

</style>

 

Thanks

Exit mobile version