How to Invert Hex Color in PHP
Snippet
This function inverts the HEX color(white to black, blue to yellow, etc.):
<?php
function hexInvert(string $color):string {
$color = trim($color);
$prependHash = false;
if (strpos($color, '#') !== false) {
$prependHash = true;
$color = str_replace('#', '', $color);
}
$len = strlen($color);
if($len==3 || $len==6){
if($len==3) $color = preg_replace('/(.)(.)(.)/', "\\1\\1\\2\\2\\3\\3", $color);
} else {
throw new \Exception("Invalid hex length ($len). Length must be 3 or 6 characters");
}
if (!preg_match('/^[a-f0-9]{6}$/i', $color)) {
throw new \Exception(sprintf('Invalid hex string #%s', htmlspecialchars($color, ENT_QUOTES)));
}
$r = dechex(255 - hexdec(substr($color, 0, 2)));
$r = (strlen($r) > 1) ? $r : '0' . $r;
$g = dechex(255 - hexdec(substr($color, 2, 2)));
$g = (strlen($g) > 1) ? $g : '0' . $g;
$b = dechex(255 - hexdec(substr($color, 4, 2)));
$b = (strlen($b) > 1) ? $b : '0' . $b;
return ($prependHash ? '#' : '') . $r . $g . $b;
}
// Example of use
echo hexInvert('#000'); // #ffffff
echo PHP_EOL.'<br>'.PHP_EOL;
echo hexInvert('ff1100'); // 00eeff