PHP-如何将标记添加到第二个标记,以及最后一个标记之后?
如何将标签添加到第二个标签,以及最后一个标签之后?(PHP)PHP-如何将标记添加到第二个标记,以及最后一个标记之后?,php,text,Php,Text,如何将标签添加到第二个标签,以及最后一个标签之后?(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> ....
例如:
<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
文本。。。短文优先
文本,文本,文本,文本…-第二
文本,文本,文本,文本…-第三
文本,文本,文本,文本…-第四
.... 正确的方法是使用dom文档:这里有一些示例代码,希望它能帮助您理解DOMDocuments是如何工作的,有关更多信息,请访问php文档:
代码:
$str='文本。。。短文优先
文本,文本,文本,文本…-第二
文本,文本,文本,文本…-第三
文本,文本,文本,文本…-第四名;
$dom=新的DOMDocument();
$dom->loadHTML($str);
$dom->formatOutput=true;
//引用和设置所需的元素
$body=$dom->getElementsByTagName('body')->item(0);
$p_list=$dom->getElementsByTagName('p');
$div=$dom->createElement('div');
$div->setAttribute('class','long text');
$length=$p_list->length;
//将p移动到已创建的$div元素
对于($i=0;$i<$length;$i++){
如果($i==0)继续;
$item=$p_list->item(1);
$div->appendChild($item);
}
//将填充的$div追加到正文
$body->appendChild($div);
//输出
$string=$dom->saveHTML();
echo$字符串;
首先,这些被称为“标签”,属性应该是文本(粗体是属性)。哎呀,我忘了。纠正我的问题。谢谢,我想你会等很长时间,等待一个问题不清楚的答案。请更新您的问题以使其更清楚。您是从数据库生成的吗?你只是想用PHP标签添加那些div吗?我真的没有问任何问题。救命啊,你可以解决这个问题。你明白了吗question@Areku_UA“我真的没有问任何问题。”这是问答平台上的问题。看:非常感谢你的回答!
<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>'
$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;