2011-02-02 42 views
1

如何在下面的脚本中对我的内容中的关键字外观进行不区分大小写的比较?不区分大小写的文本()与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

相当多重复http://stackoverflow.com/questions/625986/how-can-use-xpath-to-perform-a-case-insensitive-search-and-support-non-english – rik 2011-02-02 18:38:05

+0

@rik ,我试图用translate路由替换成我的xquery(并且用这个信息更新了我的问题),但是当我这样做时,根本不做替换。 – 2011-02-02 19:37:47

+0

[在php中区分大小写的xpath搜索]可能的重复(http://stackoverflow.com/questions/3238989/case-insensitive-xpath-searching-in-php/3240155#3240155) – Gordon 2011-02-02 23:23:18

回答

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

正确的表达应该测试是否小写的文本包含小写的关键字

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

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

替换您尝试:

contains(translate(text(), 'ABC… 

contains(translate(., 'ABC…