$html = '<h1>Man Gnoy artrit in the text</h1>
Some text about artrit.
<p>There are many types of side. Gnoy artrit may be other side and gnoy artrit once more.</p>
Non gnoy artrit
<a href="#">Anoter text gnoy artrit side.</a>
Some ending text.
Non gnoy artrit
<h5>Anoter text of gnoy artrit side.</h5>
Some ending text.';
$dom = new DomDocument();
$dom->loadHTML($html);
$keyword = 'gnoy artrit';
$xpath = new DomXPath($dom);
$nodes = $xpath->query("
//text()[contains(
translate(., 'ABCDEFGHJIKLMNOPQRSTUVWXYZ', 'abcdefghjiklmnopqrstuvwxyz'),
'$keyword')
and not(ancestor::h1)
and not(ancestor::h2)
and not(ancestor::h3)
and not(ancestor::h4)
and not(ancestor::h5)
and not(ancestor::h6)
and not(ancestor::a)]
");
foreach ($nodes as $node) {
$replace = function($node, $keyword) use (&$replace) {
$startPos = stripos($node->textContent, $keyword);
if ($startPos === false) {
return;
}
$keynode = $node->splitText($startPos);
$restnode = $keynode->splitText(strlen($keyword));
$replacement = new DOMElement('strong', $keynode->textContent);
$node->parentNode->replaceChild($replacement, $keynode);
$replace($restnode, $keyword);
};
$replace($node, $keyword);
}
echo $html;
echo '<hr>';
echo $dom->saveHTML();