Skip to content

Commit 6bf1dfe

Browse files
committed
[ADD] shortenRGBColors
1 parent 149fee4 commit 6bf1dfe

File tree

1 file changed

+33
-0
lines changed

1 file changed

+33
-0
lines changed

src/CSS.php

Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -316,6 +316,7 @@ public function execute($path = null, $parents = array())
316316
$css = $this->replace($css);
317317

318318
$css = $this->stripWhitespace($css);
319+
$css = $this->shortenRGBColors($css);
319320
$css = $this->shortenHEXColors($css);
320321
$css = $this->shortenZeroes($css);
321322
$css = $this->shortenFontWeights($css);
@@ -562,6 +563,38 @@ function ($match) use ($colors) {
562563
);
563564
}
564565

566+
/**
567+
* Shorthand RGB color codes.
568+
* rgb(255,0,0) -> #f00.
569+
*
570+
* @param string $content The CSS content to shorten the RGB color codes for
571+
*
572+
* @return string
573+
*/
574+
protected function shortenRGBColors($content)
575+
{
576+
/*
577+
https://developer.mozilla.org/en-US/docs/Web/CSS/color_value/rgb()
578+
*/
579+
// THX @ https://www.regular-expressions.info/numericranges.html
580+
$dec = '([01]?[0-9]?[0-9]|2[0-4][0-9]|25[0-5])';// [000-255]
581+
582+
// remove alpha channel if it's pointless ..
583+
$content = preg_replace("/(rgb)a?\(([^,\s]+)[,\s]([^,\s]+)[,\s]([^,\s]+)\s?[,\/]\s?1(?:[\.\d]*|00%)?\)/i", '$1($2 $3 $4)', $content);
584+
585+
// replace `transparent` with shortcut ..
586+
#$content = preg_replace("/rgba?\([^,\s]+[,\s][^,\s]+[,\s][^,\s]+\s?[,\/]\s?0(?:[\.0%]*)?\)/i", '#0000', $content); CHECK safari
587+
588+
return preg_replace_callback(
589+
"/rgb\($dec[,\s]$dec[,\s]$dec\)/i",
590+
function ($match)
591+
{
592+
return sprintf('#%02x%02x%02x', $match[1],$match[2],$match[3]);
593+
},
594+
$content
595+
);
596+
}
597+
565598
/**
566599
* Shorten CSS font weights.
567600
*

0 commit comments

Comments
 (0)