Skip to content

Instantly share code, notes, and snippets.

@frecklebit
Last active March 18, 2024 20:34
Show Gist options
  • Save frecklebit/9feba99167a24a95a46dd92f9a6c4133 to your computer and use it in GitHub Desktop.
Save frecklebit/9feba99167a24a95a46dd92f9a6c4133 to your computer and use it in GitHub Desktop.
PHP Convert RGB to Hex
<?php
/**
* Convert rgb colors to hex
*
* @since TimberPress 1.0.0
* @param string $hex Hex color code
* @return mixed rgb value
*/
if ( ! function_exists( 'timberpress_rgb_to_hex' ) ) :
function timberpress_rgb_to_hex( $color ) {
$pattern = "/(\d{1,3})\,?\s?(\d{1,3})\,?\s?(\d{1,3})/";
// Only if it's RGB
if ( preg_match( $pattern, $color, $matches ) ) {
$r = $matches[1];
$g = $matches[2];
$b = $matches[3];
$color = sprintf("#%02x%02x%02x", $r, $g, $b);
}
return $color;
}
endif;
@nobel-512
Copy link

Great work 👍

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment