PHP - 如何添加标签到第二个标签,并在最后一个标签?
问题描述:
如何将标签< DIV>添加到第二个标签< P>,最后标签</P>后? (PHP)
例如: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;
+0
非常感谢您的回答! – 2013-05-01 09:42:02
开始,那些被称为“标签”,属性将是
哎呀,我忘了。纠正我的问题。谢谢 – 2013-04-30 11:08:25
我想你会等很久才能回答一个不清楚的问题。请更新您的问题,以便更清楚。你是从数据库生成的吗?你只是想用PHP标签添加这些div吗? – user1048676 2013-04-30 11:10:22