Posted By

koncept on 04/13/08


Tagged

hex colour color convert inverse


Versions (?)

Who likes this?

3 people have marked this snippet as a favorite

jonhenshaw
vali29
canberkol


Inverse Hex Color


 / Published in: PHP
 

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-10-05
  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. break;
  25. case 6:
  26. break;
  27. default:
  28. trigger_error("Invalid hex length ($len). Must be a minimum length of (3) or maxium of (6) characters", E_USER_ERROR);
  29. }
  30.  
  31. if(!preg_match('/^[a-f0-9]{6}$/i',$color)) {
  32. $color = htmlentities($color);
  33. trigger_error( "Invalid hex string #$color", E_USER_ERROR );
  34. }
  35.  
  36. $r = dechex(255-hexdec(substr($color,0,2)));
  37. $r = (strlen($r)>1)?$r:'0'.$r;
  38. $g = dechex(255-hexdec(substr($color,2,2)));
  39. $g = (strlen($g)>1)?$g:'0'.$g;
  40. $b = dechex(255-hexdec(substr($color,4,2)));
  41. $b = (strlen($b)>1)?$b:'0'.$b;
  42.  
  43. return ($prependHash?'#':NULL).$r.$g.$b;
  44. }
  45.  
  46. // Demo
  47. echo inverseHex('#000000'); // #ffffff
  48. ?>

Report this snippet  

Comments

RSS Icon Subscribe to comments
Posted By: Raisor on October 5, 2008

Shouldn't this: case 3: $color=preg_replace("/(.)(.)(.)/","\1\1\2\2\3\3",$color); case 6:

actually be this: case 3: case 6: $color=preg_replace("/(.)(.)(.)/","\1\1\2\2\3\3",$color);

Posted By: Raisor on October 5, 2008

Guess my formatting wasn't correct, I was asking: Shouldn't this:

case 3: 
       $color=preg_replace("/(.)(.)(.)/","\1\1\2\2\3\3",$color); 
case 6:

actually be this:

case 3: 
case 6: 
       $color=preg_replace("/(.)(.)(.)/","\1\1\2\2\3\3",$color);

Posted By: koncept on October 5, 2008

You caught something there... There should be a break after case 3. Corrected.

You need to login to post a comment.