Search code examples
phphtmlhashcolors

How can I convert strings to an html color code hash?


I'd like to represent strings as arbitrary html colors.

Example:

"blah blah" = #FFCC00
"foo foo 2" = #565656

It doesn't matter what the actual color code is, so long as it's a valid hexadecimal HTML color code and the whole spectrum is fairly well represented.

I guess the first step would be to do an MD5 on the string and then somehow convert that to hexadecimal color code?

Update: Usage example is to generate a visual report of file requests on a server. The colors don't have to look pretty, it's more so a human brain can detect patterns, etc in the data more readily.


Solution

  • Thanks for the pointers, this seems to do a competent job:

    function stringToColorCode($str) {
      $code = dechex(crc32($str));
      $code = substr($code, 0, 6);
      return $code;
    }
    
    $str = 'test123';
    print '<span style="background-color:#'.stringToColorCode($str).'">'.$str.'</span>';