DOMdocument查询:如果首次出现关键字匹配条件,退出?

时间:2011-02-02 18:44:01

标签: php domdocument

如何修改下面的脚本,以便如果内容字符串中第一次出现的关键字已用粗体或强力括起来,我是否会转义节点替换?

    $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 个答案:

答案 0 :(得分:1)

在该特定情况下,使用evaluate代替query并更改XPath以计算与高亮标准匹配的元素

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

如果返回> 1,则关键字已经包含在内。您必须在另一个查询之前运行此查询。