We Recommend

Wicked Cool PHP: Real-World Scripts That Solve Difficult Problems Wicked Cool PHP: Real-World Scripts That Solve Difficult Problems
Wicked Cool PHP contains a wide variety of scripts to process credit cards, check the validity of email addresses, template HTML, and serve dynamic images and text.


Posted By

koncept on 04/13/08


Tagged

hex colour color convert inverse


Versions (?)


Who likes this?

1 person has marked this snippet as a favorite

jonhenshaw


Inverse Hex Color


Published in: PHP 


Sorry to those who previously bookmarked this. In an attempt to delete a previous version that had a logic flaw, I accidently deleted the entire snippet. Anyway, here is a much improved version. Any comments/suggestions are always welcome.

  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.  * @param string $color Hex color to flip
  6.  * @return string Reversed hex color
  7.  * @author Koncept
  8.  *
  9.  * Last Update: 2008-04-13
  10.  */
  11. function inverseHex( $color )
  12. {
  13. $color = trim($color);
  14. $prependHash = FALSE;
  15.  
  16. if(strpos($color,'#')!==FALSE) {
  17. $prependHash = TRUE;
  18. $color = str_replace('#',NULL,$color);
  19. }
  20.  
  21. switch($len=strlen($color)) {
  22. case 3:
  23. $color=preg_replace("/(.)(.)(.)/","\\1\\1\\2\\2\\3\\3",$color);
  24. case 6:
  25. break;
  26. default:
  27. trigger_error("Invalid hex length ($len). Must be (3) or (6)", E_USER_ERROR);
  28. }
  29.  
  30. if(!preg_match('/[a-f0-9]{6}/i',$color)) {
  31. $color = htmlentities($color);
  32. trigger_error( "Invalid hex string #$color", E_USER_ERROR );
  33. }
  34.  
  35. $r = dechex(255-hexdec(substr($color,0,2)));
  36. $r = (strlen($r)>1)?$r:'0'.$r;
  37. $g = dechex(255-hexdec(substr($color,2,2)));
  38. $g = (strlen($g)>1)?$g:'0'.$g;
  39. $b = dechex(255-hexdec(substr($color,4,2)));
  40. $b = (strlen($b)>1)?$b:'0'.$b;
  41.  
  42. return ($prependHash?'#':NULL).$r.$g.$b;
  43. }
  44.  
  45. // Demo
  46. echo inverseHex('#000000'); // #ffffff
  47. ?>

Report this snippet 

You need to login to post a comment.