2013-04-30 45 views
-4

如何將標籤< 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>' 
+1

開始,那些被稱爲「標籤」,屬性將是

text
(粗體的東西是屬性) – aleation 2013-04-30 11:05:35

+0

哎呀,我忘了。糾正我的問題。謝謝 – 2013-04-30 11:08:25

+0

我想你會等很久才能回答一個不清楚的問題。請更新您的問題,以便更清楚。你是從數據庫生成的嗎?你只是想用PHP標籤添加這些div嗎? – user1048676 2013-04-30 11:10:22

回答

1

正確的方法將使用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

相關問題