PHP get first paragraph from a string function

Here’s a useful PHP function to return the first paragraph from a HTML text string. It involves finding the character position of the first closing “p” tag from the first paragraph.

Add the following function somewhere in you PHP (I usually have a global functions file).

<?php 
    function getFirstPara($string){
        $string = substr($string,0, strpos($string, "</p>")+4);
        return $string;
    }
?>

Then call the function, passing the string variable:

<?php echo getFirstPara($HTMLString; ?>

If you wanted to remove the paragraph tags from the HTML, the function would change to:

<?php 
    function getFirstPara($string){
        $string = substr($string,0, strpos($string, "</p>")+4);
        $string = str_replace("<p>", "", str_replace("<p/>", "", $string));
        return $string;
    }
?>

That’s it!

5 Responses to “PHP get first paragraph from a string function”

  1. Gustavo says:

    For remove the paragraph tag use strip_tags

  2. Rory says:

    Very helpful, thanks for sharing!

  3. Mtho says:

    How about the second paragraph? Is it possible

  4. rahul says:

    nice one

  5. Michael says:

    Thank you, just what I needed.

Leave a Reply

*