Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
This function is for parsing legacy color values. It is based on the WHATWG specs.
<?php
function parseColorString($str, $format = 'hex') {
$str = strtolower(trim($str));
// prevent errors for an empty string and ignore 'transparent'
if ($str == '' || $str == 'transparent') {
return false;
}
// replace nonvalid hex characters with 0
$str = preg_replace('/[^0-9a-f]/u', 0, $str);
// zero-pad the string to the next multiple of 3,
// so it can be split into 3 parts of the same size
$nextMultiple = ceil(strlen($str) / 3) * 3;
$str = str_pad($str, $nextMultiple, 0);
$colorChannels = str_split($str, strlen($str) / 3);
// truncate from left to (rightmost) 8 chars
foreach ($colorChannels as &$channel) {
$channel = substr($channel, -8);
}
// remove leading zeros equally on all three color channels
while ($colorChannels[0][0] . $colorChannels[1][0] . $colorChannels[2][0] == '000') {
$colorChannels[0] = substr($colorChannels[0], 1);
$colorChannels[1] = substr($colorChannels[1], 1);
$colorChannels[2] = substr($colorChannels[2], 1);
}
// cut or prepend with zeros until 2 chars long
foreach ($colorChannels as &$channel) {
$channel = str_pad($channel, 2, 0, STR_PAD_LEFT);
$channel = substr($channel, 0, 2);
}
switch ($format) {
case '':
return $colorChannels;
break;
case 'rgb':
return vsprintf('rgb(%d, %d, %d)', array_map('hexdec', $colorChannels));
break;
case 'hex':
default:
return vsprintf('#%s%s%s', $colorChannels);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.