Regular Expressions 101

Community Patterns

Community Library Entry

2

Regular Expression
PCRE2 (PHP >=7.3)

/
rgba?\((?<r>[.\d]+)[, ]+(?<g>[.\d]+)[, ]+(?<b>[.\d]+)(?:\s?[,\/]\s?(?<a>[.\d]+%?))?\)
/
ig

Description

JS function to convert RGB(A) to HEX color for single values:

/**
 * @param {string} color the RGB(A) color
 * @return {string} the HEX color
 */
function rgba2hex(color)
{
  const rgb = color.replace(/,\s+/g, ',').match(/^rgba?\(([.\d]+)[, ]+([.\d]+)[, ]+([.\d]+)[, ]?([.\d]+)?\)$/i);
  let hex = (parseInt(rgb[1], 10) | 1 << 8).toString(16).slice(1)
    + (parseInt(rgb[2], 10) | 1  << 8).toString(16).slice(1)
    + (parseInt(rgb[3], 10) | 1  << 8).toString(16).slice(1);
  if (rgb[4]) {
    if (rgb[4].startsWith('.')) {
      rgb[4] = '0' + rgb[4];
    }
    hex += ((parseInt(rgb[4], 10) * 255) | 1 << 8).toString(16).slice(1);
  }
  return '#' + hex;
}

PHP function using regexp to convert RGB/RGBA to HEX colors in CSS:

function rgb2Hex(string $css)
{
    return preg_replace_callback(
        '/rgba?\((?<r>[.\d]+)[, ]+(?<g>[.\d]+)[, ]+(?<b>[.\d]+)(?:\s?[,\/]\s?(?<a>[.\d]+%?))?\)/i',
        static function (array $matches) {
            $matches['r'] = ceil($matches['r']);
            $matches['g'] = ceil($matches['g']);
            $matches['b'] = ceil($matches['b']);
            if (isset($matches['a'])) {
                if (str_ends_with($matches['a'], '%')) {
                     // 2.55 is 1%
                     $matches['a'] = 2.55 * (float) substr($matches['a'], -1);
                } else {
                    if ($matches['a'][0] === '.') {
                        $matches['a'] = '0' . $matches['a'];
                    }
                    $matches['a'] = 255 * (float) $matches['a'];
                }
                $matches['a'] = ceil($matches['a']);
                $hex = dechex(($matches['r'] << 24) | ($matches['g'] << 16) | ($matches['b'] << 8) | $matches['a']);
                return '#' . str_pad($hex, 8, '0', STR_PAD_LEFT);
            }
            $hex = dechex(($matches['r'] << 16) | ($matches['g'] << 8) | $matches['b']);
            return '#' . str_pad($hex, 6, '0', STR_PAD_LEFT);
        },
        $css
    );
}

Test:

$css = <<<'CSS'
color: rgb(34, 12, 64, 0.6);
color: rgba(34, 12, 64, 0.6);
color: rgba(34, 12, 64, .6);
color: rgb(34 12 64 / 0.6);
color: rgba(34 12 64 / 0.3);
color: rgb(34.0 12 64 / 60%);
color: rgba(34.6 12 64 / 30%);
color: rgba(0, 255, 255);
color: rgba(0, 255, 255);
color: rgba(0, 255, 255, .5);
color: rgba(0, 255, 255, 0.5);
color: rgba(0 255 255 / 0.5);
CSS;
echo rgb2Hex($css);

Result:

color: #220c4010;
color: #220c4010;
color: #220c4010;
color: #220c4010;
color: #220c4008;
color: #220c4000;
color: #230c4000;
color: #00ffff;
color: #00ffff;
color: #00ffff0d;
color: #00ffff0d;
color: #00ffff0d;
Submitted by WinterSilence - 2 years ago