PHP -如何在第二个标签和最后一个标签之后添加一个标签


PHP - How to add an tag to the second tag, and after the last tag?

如何添加标签

到第二个标签

,最后一个标签

?(PHP)
例如:
<p>text... short text - first</p>
<p>text, text, text, text... - Second</p>
<p>text, text, text, text... - Third</p>
<p>text, text, text, text... - Fourth</p> 
....       <-- some texts

:

<p>text... short text - first</p>
<div class="long-text">                             <-- add tag '<div ...>'
   <p>text, text, text, text... - Second</p>
   <p>text, text, text, text... - Third</p>
   <p>text, text, text, text... - Fourth</p>
   ....       <-- some texts
</div>                                              <-- close tag '</div>'

正确的方法是使用dom文档:这里有一些示例代码,希望它能帮助你理解DOMDocuments是如何工作的,更多信息请参阅php文档:http://it1.php.net/manual/es/book.dom.php

代码:

$str = '<p>text... short text - first</p>
<p>text, text, text, text... - Second</p>
<p>text, text, text, text... - Third</p>
<p>text, text, text, text... - Fourth</p>';

$dom = new DOMDocument();
$dom -> loadHTML($str);
$dom->formatOutput = true;
//referencing and setting the needed elements
$body = $dom->getElementsByTagName('body')->item(0);
$p_list = $dom->getElementsByTagName('p');
$div = $dom->createElement('div');
$div->setAttribute('class', 'long-text');
$length = $p_list->length;
//moving the p's to the created $div element
for($i = 0; $i < $length; $i++){
    if($i == 0)continue;
    $item = $p_list->item(1);
    $div->appendChild($item);
}
//appending the filled up $div to the body
$body->appendChild($div);
//output
$string = $dom->saveHTML();
echo $string;