duanchensou8685 2013-04-21 18:54
浏览 10
已采纳

如何显示前两个段落? 然后是剩下的段落? - PHP

I have 4 paragraphs of text in one string. Each paragraph is surrounded with <p></p>.

  1. My first goal is to output the first 2 paragraphs.
  2. My second goal it to output the remaining paragraphs somewhere else on the page. I could sometimes be dealing with strings containing more than 4 paragraphs.

I've searched on the web for anything already out there. There's quite a bit about displaying just the first paragraph, but nothing I could find about displaying paragraphs 1-2 and then the remaining paragraphs. Can anyone help here?

Not sure which to use if any, substr, strpos, etc.....?

EDIT - thanks for your answers, to clarify, the paragraphs don't contain HTML at the moment, but yes I will need the option to have HTML within each paragraph.

  • 写回答

2条回答 默认 最新

  • dongsi2317 2013-04-21 19:11
    关注

    Use DOMDocument

    Initialize with:

    $dom = new DOMDocument;
    $dom->loadHTML($myString);
    $p = $dom->getElementsByTagName('p');
    

    If each can contains other HTML elements(or not), create a function:

    function getInner(DOMElement $node) {
        $tmp = "";
        foreach($node->childNodes as $c) {
            $tmp .= $c->ownerDocument->saveXML($c);
        }
        return $tmp;
    }
    

    and then use that function when needing the paragraph like so:

    $p1 = getInner($p->item(0));
    

    You can read more about DOMDocument here

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 公交车和无人机协同运输
  • ¥15 stm32代码移植没反应
  • ¥15 matlab基于pde算法图像修复,为什么只能对示例图像有效
  • ¥100 连续两帧图像高速减法
  • ¥15 组策略中的计算机配置策略无法下发
  • ¥15 如何绘制动力学系统的相图
  • ¥15 对接wps接口实现获取元数据
  • ¥20 给自己本科IT专业毕业的妹m找个实习工作
  • ¥15 用友U8:向一个无法连接的网络尝试了一个套接字操作,如何解决?
  • ¥30 我的代码按理说完成了模型的搭建、训练、验证测试等工作(标签-网络|关键词-变化检测)