С помощью приведенных PHP-функции можно заменить цвета в CSS-стилях.
function hexToRgb($hex)
{
$hex = trim($hex, ' #');
$size = strlen($hex);
if ($size == 3 || $size == 4) {
$parts = str_split($hex, 1);
$hex = '';
foreach ($parts as $row) {
$hex .= $row . $row;
}
}
$dec = hexdec($hex);
$rgb = array();
if ($size == 3 || $size == 6) {
$rgb['red'] = 0xFF & ($dec >> 0x10);
$rgb['green'] = 0xFF & ($dec >> 0x8);
$rgb['blue'] = 0xFF & $dec;
return 'rgb(' . implode(',', $rgb) . ')';
} elseif ($size == 4 || $size == 8) {
$rgb['red'] = 0xFF & ($dec >> 0x16);
$rgb['green'] = 0xFF & ($dec >> 0x10);
$rgb['blue'] = 0xFF & ($dec >> 0x8);
$rgb['alpha'] = 0xFF & $dec;
$rgb['alpha'] = round(($rgb['alpha'] / (255 / 100)) / 100, 2);
return 'rgba(' . implode(',', $rgb) . ')';
} else {
return false;
}
return $rgb;
}
function CssHexToRgb($css)
{
return preg_replace_callback(
'/#(?:[0-9a-f]{3,8})/i',
function($matches){
return hexToRgb($matches[0], true);
},
$css
);
}
$css = '
body {
color: #000;
background: #4545;
}
header {
color: #111111;
background: #00000080;
}
';
echo CssHexToRgb($css);
exit();
Результат:
body {
color: rgb(0,0,0);
background: rgba(17,85,68,0.33);
}
header {
color: rgb(17,17,17);
background: rgba(0,0,0,0.5);
}
function rgbToHex($color)
{
preg_match_all("/\((.+?)\)/", $color, $matches);
if (!empty($matches[1][0])) {
$rgb = explode(',', $matches[1][0]);
$size = count($rgb);
if ($size == 3 || $size == 4) {
if ($size == 4) {
$alpha = array_pop($rgb);
$alpha = floatval(trim($alpha));
$alpha = ceil(($alpha * (255 * 100)) / 100);
array_push($rgb, $alpha);
}
$result = '#';
foreach ($rgb as $row) {
$result .= str_pad(dechex(trim($row)), 2, '0', STR_PAD_LEFT);
}
return $result;
}
}
return false;
}
function CssRgbToHex($css)
{
return preg_replace_callback(
'/((rgba)\((\d{1,3},\s?){3}(1|0?\.?\d+)\)|(rgb)\(\d{1,3}(,\s?\d{1,3}){2}\))/i',
function($matches){
return rgbToHex($matches[0]);
},
$css
);
}
$css = '
body {
color: rgb(0,0,0);
background: rgba(17,85,68,0.33);
}
header {
color: rgb(17,17,17);
background: rgba(0,0,0,0.5);
}
';
echo CssRgbToHex($css);
Результат:
body {
color: #000000;
background: #11554455;
}
header {
color: #111111;
background: #00000080;
}