Created
November 18, 2022 06:48
-
-
Save paboden/95d545068ca10a208628208ff7cdad40 to your computer and use it in GitHub Desktop.
Drupal 8/9/php: Grab first paragraph from string of html
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| /** | |
| * 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