I use the below function found in Highlight keywords in a paragraph for highlighting keywords in a string. Thus it generates this warning:
Warning: DOMDocument::loadHTML() [domdocument.loadhtml]: htmlParseEntityRef: expecting ';' in Entity, line: 1 in /../ on line 118
Following this thread Warning: DOMDocument::loadHTML(): htmlParseEntityRef: expecting ';' in Entity, the answers suggests using html entitiy encoding but doing that misses the whole purpose of using DOM to search through the string and highlighting without breaking the tags. E.g. a htmlentities and html_entity_decode would highlight alla occurences.
How should I tackle this? Or is there some other problem with the function that I am missing?
function highlight($string,$query){
$keywords = explode(" ",$query);
//define
$keywordsCIS = array();
foreach($keywords as $value){
$lcValue = strtolower($value);
$keywordsCIS[] = $value;
$keywordsCIS[] = $lcValue;
$keywordsCIS[] = ucfirst($lcValue);
$keywordsCIS[] = strtoupper($lcValue);
}
$dom = new DomDocument();
$dom ->recover = true;
$dom -> strictErrorChecking = false;
$dom -> loadHtml($string);
$xpath = new DomXpath($dom);
foreach ($keywordsCIS as $keyword) {
$elements = $xpath->query('//*[contains(.,"' . $keyword . '")]');
foreach ($elements as $element) {
foreach ($element->childNodes as $child) {
if (!$child instanceof DomText) continue;
$fragment = $dom->createDocumentFragment();
$text = $child->textContent;
$stubs = array();
while (($pos = stripos($text, $keyword)) !== false) {
$fragment->appendChild(new DomText(substr($text, 0, $pos)));
$word = substr($text, $pos, strlen($keyword));
$highlight = $dom->createElement('strong');
$highlight->appendChild(new DomText($word));
$highlight->setAttribute('class', 'kw');
$fragment->appendChild($highlight);
$text = substr($text, $pos + strlen($keyword));
}
if (!empty($text)) $fragment->appendChild(new DomText($text));
$element->replaceChild($fragment, $child);
}
}
}
//$string = $dom->saveXml($dom->getElementsByTagName('body')->item(0)->firstChild);
$string = $dom->saveHTML();
return $string;
}