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; } ?>
Very helpful, thanks for sharing!
How about the second paragraph? Is it possible
Thank you, just what I needed.
I will use the code in my WordPress site to get first paragraph and set it post entry automatically.
Thank you very much!
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?
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.
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.
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!
If you have anything before your first p tag (like a heading) this returns that as well
Sorry, forgot to include the tweak:
`substr($string, strpos($string,””)-3, strpos($string, “”)+4);`
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!
For remove the paragraph tag use strip_tags