Запрос DOMdocument: если первое появление ключевого слова соответствует критериям, выйти? - PullRequest
0 голосов
/ 02 февраля 2011

Как мне изменить приведенный ниже скрипт так, чтобы, если первое появление ключевого слова в строке содержимого уже было выделено жирным или сильным шрифтом, я избежал замены узла?

    $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();

1 Ответ

1 голос
/ 02 февраля 2011

В этом конкретном случае используйте evaluate вместо query и измените XPath для подсчета элементов, соответствующих критериям выделения, с помощью

"count(//text()[contains(.,'$keyword') and (ancestor::b or ancestor::strong)])"

Если это возвращает > 1, ключевое слово уже заключено. Вы должны выполнить этот запрос перед другим запросом.

...