While adjusting color values in PHP, I searched for a way to transform rgb() and rgba() to its hex code equivalents since I like those more. And since the hex notation in CSS allows defining an alpha channel for this since quite some time, there’s no showstopper to build a solution for this. But since this alpha channel notation is relatively new, I couldn’t find any code snippet in the wild that does what I like to. So I wrote it myself.

/**
 * Convert rgb() or rgba() to #rrggbbaa for hex codes.
 * 
 * @param	string	$color The RGB(A) color
 * @return	string The color hex code
 */
function rgb_to_hex( string $color ): string {
	$has_alpha = false;
	
	if ( strpos( $color, 'rgba' ) === 0 ) {
		$has_alpha = true;
	}
	
	$color = preg_replace( '/^rgba?\(/', '', $color );
	$color = preg_replace( '/\)$/', '', $color );
	
	if ( strpos( $color, ',' ) !== false ) {
		$color = str_replace( ' ', '', $color );
		$values = explode( ',', $color );
	}
	else {
		$color = str_replace( '/', ' ', $color );
		$color = preg_replace( '/\s{2,}/', ' ', $color );
		$values = explode( ' ', $color );
	}
	
	if ( $has_alpha && count( $values ) === 4 ) {
		$color = sprintf( '%02x%02x%02x%02x', $values[0], $values[1], $values[2], $values[3] * 255 );
	}
	else if ( ! $has_alpha && count( $values ) === 3 ) {
		$color = sprintf( '%02x%02x%02x', $values[0], $values[1], $values[2] ) . 'ff';
	}
	else {
		$color = '';
	}
	
	if ( empty( $color ) ) {
	    throw new Exception( 'Color could not be transformed into hex.' );
	}
	
	return '#' . $color;
}
Code language: PHP (php)

First we check whether the given code contains an alpha channel simply by checking whether rgb or rgba was given inside the string (line 8 – 12). Then I remove everything outside the color values (line 14 – 15) so that rgba(10, 10, 10, .5) becomes 10, 10, 10, .5. Since there are two notations for rgb/rgba, one with and one without colons, but the latter with a / between the rgb values and the alpha channel, depending on which version I got I build up an array just containing the raw values (line 17 – 25).

Last but not least, the values will be transformed to a hex notated string (line 27 – 32) and then either returned or an exception is thrown if the color could not be transformed successfully (line 37 – 41).

There could be more error checking for the given value, e.g. by using a regular expression like this (which is also not completely bulletproof, since it allows a syntax like rgb(10, 10, 10 / .5), which is not a valid notation):
rgba?(([0-255]+(,?\s?)){3}(,|\/)?\s?(([0-1]*.)?\d{1})?)
But for me, it is enough since I also control the values this function gets.

Leave a Reply

Your email address will not be published. Required fields are marked *