Как мне изменить приведенный ниже скрипт так, чтобы, если первое появление ключевого слова в строке содержимого уже было выделено жирным или сильным шрифтом, я избежал замены узла?
$keyword = "test";
$content = "this is a <strong>test</strong> phrase with the word "test" in it.
in this example, nothing would be changed, since the first
appearance of the keyword is already in boldface";
@$d = new DOMDocument();
@$d->loadHTML($content);
@$x = new DOMXpath($d);
@$nodes = $x->query("//text()[contains(.,'$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::b) and not(ancestor::strong)]");
if ($nodes && $nodes->length) {
$node = $nodes->item(0);
// Split just before the keyword
$keynode = $node->splitText(strpos($node->textContent, $keyword));
// Split after the keyword
$node->nextSibling->splitText(strlen($keyword));
// Replace keyword with <b>keyword</b>
$replacement = $d->createElement('strong', $keynode->textContent);
$keynode->parentNode->replaceChild($replacement, $keynode);
}
echo $d->saveHTML();