Warning: Trying to access array offset on value of type bool in /var/www/vhosts/tomelliott.com/httpdocs/wp-content/themes/tomelliott/single.php on line 12

PHP get first paragraph from a string function

02 February, 2012 by Tom Elliott

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).

")+4);
        return $string;
    }
?>

Then call the function, passing the string variable:


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

")+4);
        $string = str_replace("

", "", str_replace("

", "", $string)); return $string; } ?>

That’s it!



13 Comments

  • Gustavo says:

    For remove the paragraph tag use strip_tags

  • Rory says:

    Very helpful, thanks for sharing!

  • Mtho says:

    How about the second paragraph? Is it possible

  • rahul says:

    nice one

  • Michael says:

    Thank you, just what I needed.

  • yakup hoca says:

    Cool tip.
    I will use the code in my WordPress site to get first paragraph and set it post entry automatically.
    Thank you very much!

    • Gautham says:

      I tried this, but didn’t work. Any idea why?
      I put the function in function.php and got the HTML through get_post() (wordpress 3.51+)
      If I echo it without the function, it works. But nothing is return through the function. Any help?

  • Gautham says:

    Got it. The problem was with the content in the page. Also I found that the +4 is the number of characters retrieved from the p.

  • Neil says:

    Using strip_tags has been problematic for me when dealing with multiple languages. However a method of removing just the p tags is str_replace(array(“”, “”), “”, $content) or use preg replace for all tags.

  • Azmy Hanifa says:

    thanks alot tom, I was using a function to truncate HTML to a certain number of words but with a lot of paragraph breaks It was a problem. And then came your function as the savior!

  • Aron Duby says:

    If you have anything before your first p tag (like a heading) this returns that as well

  • Aron Duby says:

    Sorry, forgot to include the tweak:

    `substr($string, strpos($string,””)-3, strpos($string, “”)+4);`

  • Grue says:

    Exactly what I was looking for. However your code have a little bug: at line 4 instead should be
    Thanks anyway for the quick script!