2011-02-02 44 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…