Inverse Hex Color


/ Published in: PHP
Save to your folder(s)

Any comments/suggestions are always welcome.


Copy this code and paste it in your HTML
  1. <?php
  2. /**
  3.  * Inverses a provided hex color. If you pass a hex string with a
  4.  * hash(#), the function will return a string with a hash prepended
  5.  *
  6.  * @param string $color Hex color to flip.
  7.  * A 3 or 6 character hex code, with or without a leading '#'.
  8.  *
  9.  * @return string Reversed hex color
  10.  * @author Koncept
  11.  *
  12.  * Last Update: 2020-03-04
  13.  */
  14. function inverse_hex(string $color):string {
  15. $color = trim($color);
  16. $prependHash = FALSE;
  17.  
  18. if (strpos($color, '#') !== FALSE) {
  19. $prependHash = TRUE;
  20. $color = str_replace('#', NULL, $color);
  21. }
  22.  
  23. switch ($len = strlen($color)) {
  24. case 3:
  25. /** @var string $color */
  26. $color = preg_replace('/(.)(.)(.)/', "\\1\\1\\2\\2\\3\\3", $color);
  27. break;
  28. case 6:
  29. // Already acceptable, passthrough
  30. break;
  31. default:
  32. trigger_error("Invalid hex length ($len). Must be a minimum length of (3) or maxium of (6) characters",
  33. E_USER_ERROR);
  34. }
  35.  
  36. if (!preg_match('/^[a-f0-9]{6}$/i', $color)) {
  37. throw new RuntimeException(sprintf('Invalid hex string #%s', htmlspecialchars($color, ENT_QUOTES)));
  38. }
  39.  
  40. $r = dechex(255 - hexdec(substr($color, 0, 2)));
  41. $r = (strlen($r) > 1) ? $r : '0' . $r;
  42. $g = dechex(255 - hexdec(substr($color, 2, 2)));
  43. $g = (strlen($g) > 1) ? $g : '0' . $g;
  44. $b = dechex(255 - hexdec(substr($color, 4, 2)));
  45. $b = (strlen($b) > 1) ? $b : '0' . $b;
  46.  
  47. return ($prependHash ? '#' : NULL) . $r . $g . $b;
  48. }
  49.  
  50. // Demo
  51. echo inverse_hex('#000'); // #ffffff

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.