Get first paragraph with php

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.

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

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

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

That’s it!

Leave a Reply

Your email address will not be published. Required fields are marked *