はPHP

2017-01-10 2 views
1

私は大体このようなテキストのブロックにPHPで働いているを使用してHTMLのブロックにはPHP

の各出現内 を追加します決算数字タグの各発生の前に、HTMLは次のようになります。

<p>Paragraph one</p> 
<figure> 
    <img src="image1.jpg"> 
    <span>Text within span</span> 
</figure> 
<p>Paragraph two</p> 
<figure> 
    <img src="image2.jpg"> 
    <figcaption>Caption</figcaption> 
    <span>Text within span</span> 
</figure> 
<p>Paragraph three</p> 

私は(これは実際に進めるための最も明白な方法である場合は)ここから進んでするかどうかはわからないよ:

$doc = new DOMDocument(); 
@$doc->loadHTML($html); 

foreach($doc->getElementsByTagName('figure') as $element){ 
    //append <span>Text within span</span> before closing </figure> 
} 

$html = $doc->saveHTML(); 

echo $html; 
+0

[ 'createElement'](http://php.net/manual/en/domdocument.createelement.php)、[' appendChild'](のhttp:// php.net/manual/en/domnode.appendchild.php) –

答えて

1

ここに行く:

$html = ' 
    <p>Paragraph one</p> 
    <figure> 
     <img src="image1.jpg"> 
    </figure> 
    <p>Paragraph two</p> 
    <figure> 
     <img src="image2.jpg"> 
     <figcaption>Caption</figcaption> 
    </figure> 
    <p>Paragraph three</p> 
'; 

$doc = new DOMDocument(); 
@$doc->loadHTML($html); 

foreach ($doc->getElementsByTagName('figure') as $element) { 
    $span = $doc->createElement('span'); 
    $span->textContent = 'Some text here'; 

    $element->appendChild($span); 
} 

$html = $doc->saveHTML(); 

echo $html;