Skip to content

Instantly share code, notes, and snippets.

@a9un9hari
Created August 14, 2013 09:44
Show Gist options
  • Save a9un9hari/6229495 to your computer and use it in GitHub Desktop.
Save a9un9hari/6229495 to your computer and use it in GitHub Desktop.
PHP get first paragraph from a string function
<?php
function getFirstPara($string){
$string = substr($string,0, strpos($string, "</p>")+4);
return $string;
}
// If you wanted to remove the paragraph tags from the HTML
function getFirstPara2($string){
$string = substr($string,0, strpos($string, "</p>")+4);
$string = str_replace("<p>", "", str_replace("<p/>", "", $string));
return $string;
}
// Then call the function, passing the string variable
echo getFirstPara($HTMLString);
?>
@danemorgan
Copy link

This will return unexpected results in some cases. For instance in a document that has an image or a table before the first paragraph.

@randallbruder
Copy link

randallbruder commented Aug 13, 2018

This would give you the first full paragraph, skipping over any images or tables:

$string = substr($string, strpos($string, "<p"), strpos($string, "</p>")+4);

@maxksum
Copy link

maxksum commented Jan 5, 2022

$html = '<p>Lorem ipsum dolor sit amet.</p>';
preg_match('/<p>(.*?)<\/p>/s', $html, $match);
and then
echo $match[0];

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment