2011-01-28 2 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 : "제목 태그에 없습니다"예외와 함께 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); 
} 

가 참조 :