我使用Highlight keywords in a paragraph中的以下函數突出顯示字符串中的關鍵字。因此,它會生成此警告:使用DOM的PHP關鍵字higlighting
Warning: DOMDocument::loadHTML() [domdocument.loadhtml]: htmlParseEntityRef: expecting ';' in Entity, line: 1 in /../ on line 118
建議使用HTML編碼entitiy但這樣做錯過使用DOM通過字符串搜索和不破壞標籤突出的全部目的在此之後螺紋Warning: DOMDocument::loadHTML(): htmlParseEntityRef: expecting ';' in Entity,答案。例如。一個htmlentities和html_entity_decode會突出顯示alla事件。
我應該如何解決這個問題?還是有一些其他問題與我失蹤的功能?
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;
}