Updated Link
Edit:
I have tried to understand your function but it seems far too complicated for my liking
function highlight(
string $text,
array $words,
array $colors,
bool $ignoreCase = false,
string $format = '<b style="color:%s">%s</b>'
):string
{
$wordToColor = [];
$colorIdx = 0;
$re = '~\\b('.implode('|', $words).')\\b~';
if ($ignoreCase) {
$re .= 'i';
}
return preg_replace_callback
(
$re,
function ($m) use
(
$colors, $format, &$wordToColor, &$colorIdx
):string
{
$word = $m[0];
if ( ! isset($wordToColor[$word]) ) {
$wordToColor[$word] = $colors[$colorIdx];
}
$colorIdx = $colorIdx < count($colors) - 1 ? $colorIdx + 1 : 0;
$color = $wordToColor[$word];
return sprintf($format, $color, $word);
},
$text
);
}