# Posted By

koncept on 04/13/08

# Statistics

Viewed 637 times
Favorited by 2 user(s)

# Inverse Hex Color

/ Published in: PHP
`<?php/** * Inverses a provided hex color. If you pass a hex string with a * hash(#), the function will return a string with a hash prepended * * @param string \$color Hex color to flip.  *    A 3 or 6 character hex code, with or without a leading '#'.  * * @return string Reversed hex color * @author Koncept * * Last Update: 2020-03-04 */function inverse_hex(string \$color):string {  \$color = trim(\$color);  \$prependHash = FALSE;   if (strpos(\$color, '#') !== FALSE) {    \$prependHash = TRUE;    \$color = str_replace('#', NULL, \$color);  }   switch (\$len = strlen(\$color)) {    case 3:      /** @var string \$color */      \$color = preg_replace('/(.)(.)(.)/', "\\1\\1\\2\\2\\3\\3", \$color);      break;    case 6:      // Already acceptable, passthrough      break;    default:      trigger_error("Invalid hex length (\$len). Must be a minimum length of (3) or maxium of (6) characters",        E_USER_ERROR);  }   if (!preg_match('/^[a-f0-9]{6}\$/i', \$color)) {    throw new RuntimeException(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 ? '#' : NULL) . \$r . \$g . \$b;} // Demoecho inverse_hex('#000'); // #ffffff`