Convert Color Hex to RGB and RGB to Hex using PHP

This article will explain how to convert color code from HEX to RGB or HEX to RGB using PHP. We have created a PHP function for converting the color code to RGB or HEX. rgb2hex2rgb() function makes color conversion simple.

Parameter:

rgb2hex2rgb() function accept one parameter ($color) with two types of value RGB or HEX.

  • $color => Required, from which you want to convert.

    • RGB => 255,255,255 or 255 255 255 or 255.255.255
    • HEX => #FFFFFF or FFFFFF

Return Value:

Returns RGB format color code as an array if Hex color code is passed into $color parameter. Returns HEX format color code as a string if RGB color code is passed into $color parameter.

  • RGB => Array ( [r] => 255 [g] => 255 [b] => 255 )
  • HEX => #FFFFFF

rgb2hex2rgb() function is given below:

/**
*
* Author: CodexWorld
* Author URI: http://www.codexworld.com
* Function Name: rgb2hex2rgb()
* $color => HEX or RGB
* Returns RGB or HEX color format depending on given value.
*
**/
function rgb2hex2rgb($color){ 
   if(!
$color) return false
   
$color trim($color); 
   
$result false
  if(
preg_match("/^[0-9ABCDEFabcdef\#]+$/i"$color)){
      
$hex str_replace('#',''$color);
      if(!
$hex) return false;
      if(
strlen($hex) == 3):
         
$result['r'] = hexdec(substr($hex,0,1).substr($hex,0,1));
         
$result['g'] = hexdec(substr($hex,1,1).substr($hex,1,1));
         
$result['b'] = hexdec(substr($hex,2,1).substr($hex,2,1));
      else:
         
$result['r'] = hexdec(substr($hex,0,2));
         
$result['g'] = hexdec(substr($hex,2,2));
         
$result['b'] = hexdec(substr($hex,4,2));
      endif;       
   }elseif (
preg_match("/^[0-9]+(,| |.)+[0-9]+(,| |.)+[0-9]+$/i"$color)){ 
      
$rgbstr str_replace(array(',',' ','.'), ':'$color); 
      
$rgbarr explode(":"$rgbstr);
      
$result '#';
      
$result .= str_pad(dechex($rgbarr[0]), 2"0"STR_PAD_LEFT);
      
$result .= str_pad(dechex($rgbarr[1]), 2"0"STR_PAD_LEFT);
      
$result .= str_pad(dechex($rgbarr[2]), 2"0"STR_PAD_LEFT);
      
$result strtoupper($result); 
   }else{
      
$result false;
   }
          
   return 
$result

Uses:

Use rgb2hex2rgb() function like the following.

$hexString rgb2hex2rgb('255,255,255');
$rgbArray rgb2hex2rgb('#FFFFFF');

Do you want to get implementation help, or enhance the functionality of this script? Click here to Submit Service Request

2 Comments

  1. Reza Said...
  2. Alex Said...

Leave a reply

keyboard_double_arrow_up