2011-01-28 24 views
0

以下のforeachループでは、キーワードの最初のインスタンスのみを返し、太字のタグでラップし、ループと関数を終了するための正しい構文は何ですか?DOMDocument foreach replacement

たとえば、キーワードは「blue widgets」です。だから私は

function sx_decorate_keyword($content){ 
    $keyword = "blue widgets"; 
    $d = new DOMDocument(); 
    $d->loadHTML($content); 
    $x = new DOMXpath($d); 
    foreach($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)]") as $node){ 
     //need to wrap bold tags around the first instance of the keyword, then exit the routine 
    } 
return $content; 
} 
+0

を置き換え骨董品、なぜ単にpreg_replaceを使用しないのですか? – Dmitri

+0

@Dmitri - いずれかに部分的ではありません。 –

+0

@Dmitri:おそらく、 "not in a heading tag"例外を伴うpreg_replaceの使用例を挙げることができますか? –

答えて

0

...($コンテンツ内の)文字列の最初の外観はここで私は、コンテンツを解析するために使用しているルーチンだ

<b>blue widgets</b> 

に青色のウィジェットから変更したいあなたループの途中で途切れることがあります(ブレーク)。

また、foreachを使用することはできず、代わりに最初の要素のみを処理します。

$Matches = $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($Matches && $Matches->length > 0){ 
    $myText = $Matches->item(0); 
    // now do you thing with $myText like create <b> element, append $myText as child, 
    // replaceNode $myText with new <b> node 
} 

これが機能するかどうかを確認しますが、そのようなことはない...ドミトリが述べたように

2

は、ちょうど最初のテキストノードでのみ動作します。以下の例では、キーワードを含むDOMTextノードを解析し、<b>要素内で最初のオカレンスを折り返すというアプローチをとります。

$nodes = $x->query("... your xpath ..."); 
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); 
} 

参考: