简体   繁体   English

如何显示前 2 段? 然后是剩余的段落? - PHP

[英]How Can I Display First 2 Paragraphs? And then Remaining Paragraphs? - PHP

I have 4 paragraphs of text in one string.我在一个字符串中有 4 段文本。 Each paragraph is surrounded with <p></p> .每个段落都用<p></p>包围。

  1. My first goal is to output the first 2 paragraphs.我的第一个目标是 output 的前 2 段。
  2. My second goal it to output the remaining paragraphs somewhere else on the page.我的第二个目标是 output 页面上其他地方的其余段落。 I could sometimes be dealing with strings containing more than 4 paragraphs.我有时可能会处理包含超过 4 个段落的字符串。

I've searched on the web for anything already out there.我已经在 web 上搜索了任何已经存在的东西。 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.关于仅显示第一段的内容很多,但我找不到关于显示第 1-2 段然后显示其余段落的内容。 Can anyone help here?有人可以在这里帮忙吗?

Not sure which to use if any, substr, strpos, etc.....?如果有的话,不确定使用哪个,substr、strpos 等......?

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.编辑 - 感谢您的回答,澄清一下,这些段落目前不包含 HTML,但是是的,我需要在每个段落中包含 HTML 的选项。

Use DOMDocument 使用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: 如果每个都可以包含其他HTML元素(或不包含其他HTML元素),请创建一个函数:

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 您可以在此处阅读有关DOMDocument更多信息

Use regular expression: 使用正则表达式:

    $str = '<p style="color:red;"><b>asd</b>para<img src="afs"/>graph 1</p >
        <p>paragraph 2</p>
        <p>paragraph 3</p>
        <p>paragraph 4</p>
            ';


   // preg_match_all('/<p.*>([^\<]+)<\/p\s*>/i',$str,$matches);
    //for inside html like a comment sais:
    preg_match_all('/<p[^\>]*>(.*)<\/p\s*>/i',$str,$matches);

    print_r($matches);

prints: 印刷品:

Array
(
    [0] => Array
        (
            [0] => <p style="color:red;"><b>asd</b>para<img src="afs"/>graph 1</p >
            [1] => <p>paragraph 2</p>
            [2] => <p>paragraph 3</p>
            [3] => <p>paragraph 4</p>
        )

    [1] => Array
        (
            [0] => <b>asd</b>para<img src="afs"/>graph 1
            [1] => paragraph 2
            [2] => paragraph 3
            [3] => paragraph 4
        )

)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM