【问题标题】:PHP - How to add an tag to the second tag, and after the last tag?PHP - 如何在第二个标签和最后一个标签之后添加标签?
【发布时间】:2013-04-30 11:03:35
【问题描述】:

如何在第二个标签和最后一个标签

之后添加标签? (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>'

【问题讨论】:

  • 开始,那些被称为“标签”,属性将是
    id='asdf' >text
    (粗体的东西是属性)
  • 糟糕,我忘记了。纠正我的问题。谢谢
  • 我想你会等待很长时间才能得到一个不清楚的问题的答案。请更新您的问题以更清楚。你是从数据库生成的吗?你只是想用 PHP 标签添加那些 div 吗?
  • 我并没有真正问过问题。求助,这个问题可以解决一下。你有这个问题
  • @Areku_UA “我并没有真正问过问题。”这就是问答平台上的问题。见:stackoverflow.com/faq

标签: php text


【解决方案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;

【讨论】:

  • 非常感谢您的回答!
猜你喜欢
  • 2017-06-14
  • 2022-07-23
  • 2023-03-24
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-11-28
  • 1970-01-01
相关资源
最近更新 更多