Metzed
Metzed

Reputation: 491

How Can I Display First 2 Paragraphs? And then Remaining Paragraphs? - 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.

Upvotes: 0

Views: 2830

Answers (2)

Jon
Jon

Reputation: 4736

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

Upvotes: 2

Adidi
Adidi

Reputation: 5253

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
        )

)

Upvotes: 3

Related Questions