不区分大小写的text()与DOMdocument的比较?

时间:2011-02-02 18:22:38

标签: php xpath domdocument

如何在下面的脚本中对我的内容中的关键字外观进行不区分大小写的比较?

如果我用这个......

$keyword = strtolower(rseo_getKeyword($post));

$nodes = $x->query("//text()[
    contains(
    translate(.,'ABCDEFGHJIKLMNOPQRSTUVWXYZ',
                'abcdefghjiklmnopqrstuvwxyz'),
                '$keyword')

仅对内容中已小写的关键字匹配进行替换。它似乎没有进行不区分大小写的查找。

    $keyword = rseo_getKeyword($post);
    $content = $postarray['post_content']; //error: Empty string supplied in loadHTML() when I use this.
    //$content = "this is a test phrase";
    @$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)]");
    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('b', $keynode->textContent);
        $keynode->parentNode->replaceChild($replacement, $keynode);
    }
    echo $d->saveHTML();die;

2 个答案:

答案 0 :(得分:2)

//text()
    [contains(translate(.,'ABCDEFGHJIKLMNOPQRSTUVWXYZ',
                        'abcdefghjiklmnopqrstuvwxyz'),                 
              '$keyword') 
    ] 

正确的表达式必须测试小写文本是否包含 小写的关键字

//text()
    [contains(translate(.,'ABCDEFGHJIKLMNOPQRSTUVWXYZ',
                          'abcdefghjiklmnopqrstuvwxyz'),                 
              translate('$keyword','ABCDEFGHJIKLMNOPQRSTUVWXYZ',
                                   'abcdefghjiklmnopqrstuvwxyz')                 
              ) 
    ] 

答案 1 :(得分:1)

text()函数返回上下文节点的所有文本节点子节点。当您将其作为translate()的参数调用时,上下文节点是文本节点,因此没有文本节点子节点。相反,使用.正确选择上下文节点本身。

替换你的尝试:

contains(translate(text(), 'ABC…

contains(translate(., 'ABC…