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

I agree with sje397 above that completely random colours could end up looking nasty. Rather than make a long list of nice-looking colours, I would suggest choosing a constant saturation+luminescence value, and varying the hue based on the content. To get an RGB colour from an HSL colour, you may use something similar to what's described in http://en.wikipedia.org/wiki/HSL_and_HSV#Converting_to_RGB .

Here's an example (try it in http://codepad.viper-7.com something that works, such as https://codepad.remoteinterview.io/ZXBMZWYJFO):

<?php

function hsl2rgb($H, $S, $V) {
    $H *= 6;
    $h = intval($H);
    $H -= $h;
    $V *= 255;
    $m = $V*(1 - $S);
    $x = $V*(1 - $S*(1-$H));
    $y = $V*(1 - $S*$H);
    $a = [[$V, $x, $m], [$y, $V, $m],
          [$m, $V, $x], [$m, $y, $V],
          [$x, $m, $V], [$V, $m, $y]][$h];
    return sprintf("#%02X%02X%02X", $a[0], $a[1], $a[2]);
}

function hue($tstr) {
    return unpack('L', hash('adler32', $tstr, true))[1];
}

$phrase = "Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.";
$words = [];
foreach (explode(' ', $phrase) as $word)
    $words[hue($word)] = $word;
ksort($words);
foreach ($words as $h => $word) {
    $col = hsl2rgb($h/0xFFFFFFFF, 0.4, 1);
    printf('<span style="color:%s">%s</span> ', $col, $word);
}
?>

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>';

Almost always, just using random colours will

  1. look bad
  2. conflict with the background

I would recommend creating a (longish) list of colours that work well together and with your background - then just hash the string and modulus (%) with your number of colours to get an index into the table.

public function colorFromString($string)
{
  $colors = [
    '#0074D9',
    '#7FDBFF',
    '#39CCCC',
    // this list should be as long as practical to avoid duplicates
  ];

  // generate a partial hash of the string (a full hash is too long for the % operator)
  $hash = substr(sha1($string), 0, 10);

  // determine the color index
  $colorIndex = hexdec($hash) % count($colors);

  return $colors[$colorIndex];
}