I wrote a function to highlight keywords from my search engine. The script. It is as follows:
function highlight ($keywords, $string)
{
if (!is_array($keywords))
{
$keywords = explode(" ", $keywords);
}
for ($x = 0; $x < count($keywords); $x++)
{
$string = str_replace(addslashes(htmlspecialchars($keywords[$x])), "<span class=\"highlight\">" . addslashes(htmlspecialchars($keywords[$x])) . "</span>", $string);
}
return $string;
}
The problem is, for instance, if one of my keywords was span, highlight, or any other word that would appear in the highlighting CSS code. It works fine if there is only 1 keyword, but if there are more, and one happends to occur in the highlighting code, then it breaks.
For Example: if my two keywords are truck and span, the script loops two times, and ends up like this:
I own a red <<span class="highlight">span</span> class="highlight">truck</span>
of course, this looks like crap. How can I get the script to recognize multiple keywords without having the script think that the <span> tag is part of the string on the second pass?