2012-12-18 2 views
2

dom 객체를 사용하여 용어집 툴팁의 구현을 단순화하려고합니다. 필요한 것은 단락의 텍스트 요소를 바꾸는 것이지만 단락에 포함될 수있는 앵커 태그는 바꾸지 않는 것입니다.PHP DOM을 사용하여 자식 노드를 변경하지 않고 노드 텍스트를 대체하려고합니다.

$html = '<p>Replace this tag not this <a href="#">tag</a></p>'; 
$document = new DOMDocument(); 
$document->loadHTML($html); 
$document->preserveWhiteSpace = false; 
$document->validateOnParse = true; 

$nodes = $document->getElementByTagName("p"); 
foreach ($nodes as $node) { 
    $node->nodeValue = str_replace("tag","element",$node->nodeValue); 
} 
echo $document->saveHTML(); 

내가 얻을 : 난 단지 부모 노드의 텍스트가 변경된 것을이 같은를 구현하려면 어떻게

'...<p>Replace this element not this <a href="#">tag</a></p>...' 

을하고 자식 노드 (태그) 인 :

'...<p>Replace this element not this element</p>...' 

내가 원하는 바뀌지 않았 니? 이 도움이

$html = '<p>Replace this tag not this <a href="#">tag</a></p>'; 
$document = new DOMDocument(); 
$document->loadHTML($html); 
$document->preserveWhiteSpace = false; 
$document->validateOnParse = true; 

$nodes = $document->getElementsByTagName("p"); 

foreach ($nodes as $node) { 
    while($node->hasChildNodes()) { 
     $node = $node->childNodes->item(0); 
    } 
    $node->nodeValue = str_replace("tag","element",$node->nodeValue); 
} 
echo $document->saveHTML(); 

희망 :

답변

2

이보십시오.

아래 코멘트에 폴의 질문 @ 답하려면 UPDATE, 당신은 많은 @Pushpesh을

$html = '<p>Replace this tag not this <a href="#">tag</a></p>'; 
$document = new DOMDocument(); 
$document->loadHTML($html); 
$document->preserveWhiteSpace = false; 
$document->validateOnParse = true; 

$nodes = $document->getElementsByTagName("p"); 

//create the element which should replace the text in the original string 
$elem = $document->createElement('dfn', 'tag'); 
$attr = $document->createAttribute('title'); 
$attr->value = 'element'; 
$elem->appendChild($attr); 

foreach ($nodes as $node) { 
    while($node->hasChildNodes()) { 
     $node = $node->childNodes->item(0); 
    } 
    //dump the new string here, which replaces the source string 
    $node->nodeValue = str_replace("tag",$document->saveHTML($elem),$node->nodeValue); 
} 
echo $document->saveHTML(); 
+1

감사를 만들 수 있습니다. 이것은 잘 작동합니다. while 루프가하는 일을 설명함으로써 DOM 객체를 더 잘 이해할 수있게 도와 주시겠습니까? 감사! – user1605657

+0

나는 또한 그것을 찾고 있었고 확장 질문을 가지고 있었다. 또한 용어집을 만들고 싶다면'tag '를'element'로 대체하는 대신' 태그로 바꾸고 싶다.'. 따라서 새로운 자식을 추가하고'# text' 노드를 분할해야합니다. 나는 어떻게 그것을 성취 할 것인가? – Paul

+0

@Paul 내 업데이트를 참조하십시오. –

관련 문제