PHP separate paragraph

I am writing a code for wordpress to separate paragraph using PHP. The objective is to split the content of the post into an array and echo them accordingly.

Here are my code

Read More
<?php
    $content = "<p>123</p> <p>456</p> <p>789</p>"
    $p = explode("</p>", $content);

    $i=0;
    //echo first 2 elements
    foreach ($p as $para) {
        echo $para;
        array_shift($p); //remove the first element
        $i++; //increase the element count by 1
        if ($i == 2){ break;} //if element has reach 2 meaning second paragraph, stop loop.
    }
    echo "<br>Break here<br>";
    //echo the rest of the element
    foreach ($p as $para) {
        echo $para;
    }
?>

Replace this

$content = "<p>123</p> <p>456</p> <p>789</p>"

With the following

$content = apply_filters( 'the_content', get_the_content() );
$content = str_replace( ']]>', ']]&gt;', $content );

to retrieve the content of the post with paragraph tag.

I am able to achieve my result but I am just worry of the consequences such as system overload.

Related posts

1 comment

  1. If i understand correctly, what you’re trying to accomplish, is adding a couple of <br> tags after the first two paragraphs?

    If so, this can be done alot simpler using the preg_replace method:

    $content = "<p>123</p> <p>456</p> <p>789</p>";
    echo preg_replace('/</p>/', '</p><br><br>', $content, 2);
    

Comments are closed.