Skip to content

Instantly share code, notes, and snippets.

@paboden
Created November 18, 2022 06:48
Show Gist options
  • Select an option

  • Save paboden/95d545068ca10a208628208ff7cdad40 to your computer and use it in GitHub Desktop.

Select an option

Save paboden/95d545068ca10a208628208ff7cdad40 to your computer and use it in GitHub Desktop.
Drupal 8/9/php: Grab first paragraph from string of html
/**
* Helper function to grab the first paragraph from body/html string.
*
* This is useful for pulling out the first paragraph from a body or long text field,
* and using it for a short summary or description.
*/
function MYMODULE_grab_summary_paragraph($html_string, $remove_wrapping_p_tags = FALSE) {
// Find start point of first p tag.
$opening_p_point = strpos($html_string, "<p");
// Find end point which will be used as the cutoff length.
$closing_p_point = strpos($html_string, "</p>")+4;
$summary = substr($string[0]['#text'], $opening_p_point, $closing_p_point);
// If you want to remove the wrapping p tags
if ($summary && $remove_wrapping_p_tags) {
$summary = str_replace("<p>", "", str_replace("<p/>", "", $summary));
}
return $summary;
}
// Here is a preg_match/minimized version of above.
function MYMODULE_grab_summary_paragraph($html_string, $remove_wrapping_p_tags = FALSE) {
preg_match('/<p(.*?)<\/p>/s', $html_string, $summary);
return $summary[0] && $remove_wrapping_p_tags ? str_replace("<p>", "", str_replace("<p/>", "", $summary[0])) : $summary[0]
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment